2 \usepackage[T1]{fontenc}
5 % Add a section on file I/O
6 % Write a chapter entitled ``Some Useful Modules''
8 % Should really move the Python startup file info to an appendix
10 \title{Python Tutorial
}
19 \chapter*
{Front Matter
\label{front
}}
27 Python is an easy to learn, powerful programming language. It has
28 efficient high-level data structures and a simple but effective
29 approach to object-oriented programming. Python's elegant syntax and
30 dynamic typing, together with its interpreted nature, make it an ideal
31 language for scripting and rapid application development in many areas
34 The Python interpreter and the extensive standard library are freely
35 available in source or binary form for all major platforms from the
36 Python web site,
\url{http://www.python.org
}, and can be freely
37 distributed. The same site also contains distributions of and
38 pointers to many free third party Python modules, programs and tools,
39 and additional documentation.
41 The Python interpreter is easily extended with new functions and data
42 types implemented in C or
\Cpp{} (or other languages callable from C).
43 Python is also suitable as an extension language for customizable
46 This tutorial introduces the reader informally to the basic concepts
47 and features of the Python language and system. It helps to have a
48 Python interpreter handy for hands-on experience, but all examples are
49 self-contained, so the tutorial can be read off-line as well.
51 For a description of standard objects and modules, see the
52 \citetitle[../lib/lib.html
]{Python Library Reference
} document. The
53 \citetitle[../ref/ref.html
]{Python Reference Manual
} gives a more
54 formal definition of the language. To write extensions in C or
55 \Cpp{}, read
\citetitle[../ext/ext.html
]{Extending and Embedding the
56 Python Interpreter
} and
\citetitle[../api/api.html
]{Python/C API
57 Reference
}. There are also several books covering Python in depth.
59 This tutorial does not attempt to be comprehensive and cover every
60 single feature, or even every commonly used feature. Instead, it
61 introduces many of Python's most noteworthy features, and will give
62 you a good idea of the language's flavor and style. After reading it,
63 you will be able to read and write Python modules and programs, and
64 you will be ready to learn more about the various Python library
65 modules described in the
\citetitle[../lib/lib.html
]{Python Library
73 \chapter{Whetting Your Appetite
\label{intro
}}
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
78 call or other function that is only accessible from C
\ldots Usually
79 the problem at hand isn't serious enough to warrant rewriting the
80 script in C; perhaps the problem requires variable-length strings or
81 other data types (like sorted lists of file names) that are easy in
82 the shell but lots of work to implement in C, or perhaps you're not
83 sufficiently familiar with C.
85 Another situation: perhaps you have to work with several C libraries,
86 and the usual C write/compile/test/re-compile cycle is too slow. You
87 need to develop software more quickly. Possibly perhaps you've
88 written a program that could use an extension language, and you don't
89 want to design a language, write and debug an interpreter for it, then
90 tie it into your application.
92 In such cases, Python may be just the language for you. Python is
93 simple to use, but it is a real programming language, offering much
94 more structure and support for large programs than the shell has. On
95 the other hand, it also offers much more error checking than C, and,
96 being a
\emph{very-high-level language
}, it has high-level data types
97 built in, such as flexible arrays and dictionaries that would cost you
98 days to implement efficiently in C. Because of its more general data
99 types Python is applicable to a much larger problem domain than
100 \emph{Awk
} or even
\emph{Perl
}, yet many things are at least as easy
101 in Python as in those languages.
103 Python allows you to split up your program in modules that can be
104 reused in other Python programs. It comes with a large collection of
105 standard modules that you can use as the basis of your programs --- or
106 as examples to start learning to program in Python. There are also
107 built-in modules that provide things like file I/O, system calls,
108 sockets, and even interfaces to GUI toolkits like Tk.
110 Python is an interpreted language, which can save you considerable time
111 during program development because no compilation and linking is
112 necessary. The interpreter can be used interactively, which makes it
113 easy to experiment with features of the language, to write throw-away
114 programs, or to test functions during bottom-up program development.
115 It is also a handy desk calculator.
117 Python allows writing very compact and readable programs. Programs
118 written in Python are typically much shorter than equivalent C or
119 \Cpp{} programs, for several reasons:
122 the high-level data types allow you to express complex operations in a
125 statement grouping is done by indentation instead of begin/end
128 no variable or argument declarations are necessary.
131 Python is
\emph{extensible
}: if you know how to program in C it is easy
132 to add a new built-in function or module to the interpreter, either to
133 perform critical operations at maximum speed, or to link Python
134 programs to libraries that may only be available in binary form (such
135 as a vendor-specific graphics library). Once you are really hooked,
136 you can link the Python interpreter into an application written in C
137 and use it as an extension or command language for that application.
139 By the way, the language is named after the BBC show ``Monty Python's
140 Flying Circus'' and has nothing to do with nasty reptiles. Making
141 references to Monty Python skits in documentation is not only allowed,
144 \section{Where From Here
\label{where
}}
146 Now that you are all excited about Python, you'll want to examine it
147 in some more detail. Since the best way to learn a language is
148 using it, you are invited here to do so.
150 In the next chapter, the mechanics of using the interpreter are
151 explained. This is rather mundane information, but essential for
152 trying out the examples shown later.
154 The rest of the tutorial introduces various features of the Python
155 language and system through examples, beginning with simple
156 expressions, statements and data types, through functions and modules,
157 and finally touching upon advanced concepts like exceptions
158 and user-defined classes.
160 \chapter{Using the Python Interpreter
\label{using
}}
162 \section{Invoking the Interpreter
\label{invoking
}}
164 The Python interpreter is usually installed as
165 \file{/usr/local/bin/python
} on those machines where it is available;
166 putting
\file{/usr/local/bin
} in your
\UNIX{} shell's search path
167 makes it possible to start it by typing the command
173 to the shell. Since the choice of the directory where the interpreter
174 lives is an installation option, other places are possible; check with
175 your local Python guru or system administrator. (E.g.,
176 \file{/usr/local/python
} is a popular alternative location.)
178 Typing an
\EOF{} character (
\kbd{Control-D
} on
\UNIX,
179 \kbd{Control-Z
} on DOS or Windows) at the primary prompt causes the
180 interpreter to exit with a zero exit status. If that doesn't work,
181 you can exit the interpreter by typing the following commands:
182 \samp{import sys; sys.exit()
}.
184 The interpreter's line-editing features usually aren't very
185 sophisticated. On
\UNIX{}, whoever installed the interpreter may have
186 enabled support for the GNU readline library, which adds more
187 elaborate interactive editing and history features. Perhaps the
188 quickest check to see whether command line editing is supported is
189 typing Control-P to the first Python prompt you get. If it beeps, you
190 have command line editing; see Appendix
\ref{interacting
} for an
191 introduction to the keys. If nothing appears to happen, or if
192 \code{\^P
} is echoed, command line editing isn't available; you'll
193 only be able to use backspace to remove characters from the current
196 The interpreter operates somewhat like the
\UNIX{} shell: when called
197 with standard input connected to a tty device, it reads and executes
198 commands interactively; when called with a file name argument or with
199 a file as standard input, it reads and executes a
\emph{script
} from
202 A third way of starting the interpreter is
203 \samp{\program{python
} \programopt{-c
} \var{command
} [arg
] ...
}, which
204 executes the statement(s) in
\var{command
}, analogous to the shell's
205 \programopt{-c
} option. Since Python statements often contain spaces
206 or other characters that are special to the shell, it is best to quote
207 \var{command
} in its entirety with double quotes.
209 Note that there is a difference between
\samp{python file
} and
210 \samp{python <file
}. In the latter case, input requests from the
211 program, such as calls to
\code{input()
} and
\code{raw_input()
}, are
212 satisfied from
\emph{file
}. Since this file has already been read
213 until the end by the parser before the program starts executing, the
214 program will encounter EOF immediately. In the former case (which is
215 usually what you want) they are satisfied from whatever file or device
216 is connected to standard input of the Python interpreter.
218 When a script file is used, it is sometimes useful to be able to run
219 the script and enter interactive mode afterwards. This can be done by
220 passing
\programopt{-i
} before the script. (This does not work if the
221 script is read from standard input, for the same reason as explained
222 in the previous paragraph.)
224 \subsection{Argument Passing
\label{argPassing
}}
226 When known to the interpreter, the script name and additional
227 arguments thereafter are passed to the script in the variable
228 \code{sys.argv
}, which is a list of strings. Its length is at least
229 one; when no script and no arguments are given,
\code{sys.argv
[0]} is
230 an empty string. When the script name is given as
\code{'-'
} (meaning
231 standard input),
\code{sys.argv
[0]} is set to
\code{'-'
}. When
232 \programopt{-c
} \var{command
} is used,
\code{sys.argv
[0]} is set to
233 \code{'-c'
}. Options found after
\programopt{-c
} \var{command
} are
234 not consumed by the Python interpreter's option processing but left in
235 \code{sys.argv
} for the command to handle.
237 \subsection{Interactive Mode
\label{interactive
}}
239 When commands are read from a tty, the interpreter is said to be in
240 \emph{interactive mode
}. In this mode it prompts for the next command
241 with the
\emph{primary prompt
}, usually three greater-than signs
242 (
\samp{>
\code{>
}>~
}); for continuation lines it prompts with the
243 \emph{secondary prompt
}, by default three dots (
\samp{...~
}).
244 The interpreter prints a welcome message stating its version number
245 and a copyright notice before printing the first prompt, e.g.:
249 Python
1.5.2b2 (
#1, Feb
28 1999,
00:
02:
06)
[GCC
2.8.1] on sunos5
250 Copyright
1991-
1995 Stichting Mathematisch Centrum, Amsterdam
254 Continuation lines are needed when entering a multi-line construct.
255 As an example, take a look at this
\keyword{if
} statement:
258 >>> the_world_is_flat =
1
259 >>> if the_world_is_flat:
260 ... print "Be careful not to fall off!"
262 Be careful not to fall off!
266 \section{The Interpreter and Its Environment
\label{interp
}}
268 \subsection{Error Handling
\label{error
}}
270 When an error occurs, the interpreter prints an error
271 message and a stack trace. In interactive mode, it then returns to
272 the primary prompt; when input came from a file, it exits with a
273 nonzero exit status after printing
274 the stack trace. (Exceptions handled by an
\code{except
} clause in a
275 \code{try
} statement are not errors in this context.) Some errors are
276 unconditionally fatal and cause an exit with a nonzero exit; this
277 applies to internal inconsistencies and some cases of running out of
278 memory. All error messages are written to the standard error stream;
279 normal output from the executed commands is written to standard
282 Typing the interrupt character (usually Control-C or DEL) to the
283 primary or secondary prompt cancels the input and returns to the
284 primary prompt.
\footnote{
285 A problem with the GNU Readline package may prevent this.
287 Typing an interrupt while a command is executing raises the
288 \code{KeyboardInterrupt
} exception, which may be handled by a
289 \code{try
} statement.
291 \subsection{Executable Python Scripts
\label{scripts
}}
293 On BSD'ish
\UNIX{} systems, Python scripts can be made directly
294 executable, like shell scripts, by putting the line
297 #! /usr/bin/env python
300 (assuming that the interpreter is on the user's
\envvar{PATH
}) at the
301 beginning of the script and giving the file an executable mode. The
302 \samp{\#!
} must be the first two characters of the file. Note that
303 the hash, or pound, character,
\character{\#
}, is used to start a
306 \subsection{The Interactive Startup File
\label{startup
}}
308 % XXX This should probably be dumped in an appendix, since most people
309 % don't use Python interactively in non-trivial ways.
311 When you use Python interactively, it is frequently handy to have some
312 standard commands executed every time the interpreter is started. You
313 can do this by setting an environment variable named
314 \envvar{PYTHONSTARTUP
} to the name of a file containing your start-up
315 commands. This is similar to the
\file{.profile
} feature of the
318 This file is only read in interactive sessions, not when Python reads
319 commands from a script, and not when
\file{/dev/tty
} is given as the
320 explicit source of commands (which otherwise behaves like an
321 interactive session). It is executed in the same namespace where
322 interactive commands are executed, so that objects that it defines or
323 imports can be used without qualification in the interactive session.
324 You can also change the prompts
\code{sys.ps1
} and
\code{sys.ps2
} in
327 If you want to read an additional start-up file from the current
328 directory, you can program this in the global start-up file,
329 e.g.\
\samp{if os.path.isfile('.pythonrc.py'):
330 execfile('.pythonrc.py')
}. If you want to use the startup file in a
331 script, you must do this explicitly in the script:
335 filename = os.environ.get('PYTHONSTARTUP')
336 if filename and os.path.isfile(filename):
341 \chapter{An Informal Introduction to Python
\label{informal
}}
343 In the following examples, input and output are distinguished by the
344 presence or absence of prompts (
\samp{>
\code{>
}>~
} and
\samp{...~
}): to repeat
345 the example, you must type everything after the prompt, when the
346 prompt appears; lines that do not begin with a prompt are output from
349 % I'd prefer to use different fonts to distinguish input
350 % from output, but the amount of LaTeX hacking that would require
351 % is currently beyond my ability.
353 Note that a secondary prompt on a line by itself in an example means
354 you must type a blank line; this is used to end a multi-line command.
356 Many of the examples in this manual, even those entered at the
357 interactive prompt, include comments. Comments in Python start with
358 the hash character,
\character{\#
}, and extend to the end of the
359 physical line. A comment may appear at the start of a line or
360 following whitespace or code, but not within a string literal. A hash
361 character within a string literal is just a hash character.
366 # this is the first comment
367 SPAM =
1 # and this is the second comment
368 # ... and now a third!
369 STRING = "# This is not a comment."
373 \section{Using Python as a Calculator
\label{calculator
}}
375 Let's try some simple Python commands. Start the interpreter and wait
376 for the primary prompt,
\samp{>
\code{>
}>~
}. (It shouldn't take long.)
378 \subsection{Numbers
\label{numbers
}}
380 The interpreter acts as a simple calculator: you can type an
381 expression at it and it will write the value. Expression syntax is
382 straightforward: the operators
\code{+
},
\code{-
},
\code{*
} and
383 \code{/
} work just like in most other languages (for example, Pascal
384 or C); parentheses can be used for grouping. For example:
389 >>> # This is a comment
392 >>>
2+
2 # and a comment on the same line as code
396 >>> # Integer division returns the floor:
403 Like in C, the equal sign (
\character{=
}) is used to assign a value to a
404 variable. The value of an assignment is not written:
413 A value can be assigned to several variables simultaneously:
416 >>> x = y = z =
0 # Zero x, y and z
425 There is full support for floating point; operators with mixed type
426 operands convert the integer operand to floating point:
435 Complex numbers are also supported; imaginary numbers are written with
436 a suffix of
\samp{j
} or
\samp{J
}. Complex numbers with a nonzero
437 real component are written as
\samp{(
\var{real
}+
\var{imag
}j)
}, or can
438 be created with the
\samp{complex(
\var{real
},
\var{imag
})
} function.
443 >>>
1j * complex(
0,
1)
453 Complex numbers are always represented as two floating point numbers,
454 the real and imaginary part. To extract these parts from a complex
455 number
\var{z
}, use
\code{\var{z
}.real
} and
\code{\var{z
}.imag
}.
465 The conversion functions to floating point and integer
466 (
\function{float()
},
\function{int()
} and
\function{long()
}) don't
467 work for complex numbers --- there is no one correct way to convert a
468 complex number to a real number. Use
\code{abs(
\var{z
})
} to get its
469 magnitude (as a float) or
\code{z.real
} to get its real part.
474 Traceback (most recent call last):
475 File "<stdin>", line
1, in ?
476 TypeError: can't convert complex to float; use e.g. abs(z)
483 In interactive mode, the last printed expression is assigned to the
484 variable
\code{_
}. This means that when you are using Python as a
485 desk calculator, it is somewhat easier to continue calculations, for
499 This variable should be treated as read-only by the user. Don't
500 explicitly assign a value to it --- you would create an independent
501 local variable with the same name masking the built-in variable with
504 \subsection{Strings
\label{strings
}}
506 Besides numbers, Python can also manipulate strings, which can be
507 expressed in several ways. They can be enclosed in single quotes or
517 >>> '"Yes," he said.'
519 >>> "\"Yes,\" he said."
521 >>> '"Isn\'t," she said.'
522 '"Isn\'t," she said.'
525 String literals can span multiple lines in several ways. Newlines can
526 be escaped with backslashes, e.g.:
529 hello = "This is a rather long string containing
\n\
530 several lines of text just as you would do in C.
\n\
531 Note that whitespace at the beginning of the line is\
536 which would print the following:
539 This is a rather long string containing
540 several lines of text just as you would do in C.
541 Note that whitespace at the beginning of the line is significant.
544 Or, strings can be surrounded in a pair of matching triple-quotes:
545 \code{"""
} or
\code {'''
}. End of lines do not need to be escaped
546 when using triple-quotes, but they will be included in the string.
550 Usage: thingy
[OPTIONS
]
551 -h Display this usage message
552 -H hostname Hostname to connect to
556 produces the following output:
559 Usage: thingy
[OPTIONS
]
560 -h Display this usage message
561 -H hostname Hostname to connect to
564 The interpreter prints the result of string operations in the same way
565 as they are typed for input: inside quotes, and with quotes and other
566 funny characters escaped by backslashes, to show the precise
567 value. The string is enclosed in double quotes if the string contains
568 a single quote and no double quotes, else it's enclosed in single
569 quotes. (The
\keyword{print
} statement, described later, can be used
570 to write strings without quotes or escapes.)
572 Strings can be concatenated (glued together) with the
573 \code{+
} operator, and repeated with
\code{*
}:
576 >>> word = 'Help' + 'A'
579 >>> '<' + word*
5 + '>'
580 '<HelpAHelpAHelpAHelpAHelpA>'
583 Two string literals next to each other are automatically concatenated;
584 the first line above could also have been written
\samp{word = 'Help'
585 'A'
}; this only works with two literals, not with arbitrary string
590 >>> 'str' 'ing' # <- This is ok
592 >>> string.strip('str') + 'ing' # <- This is ok
594 >>> string.strip('str') 'ing' # <- This is invalid
595 File "<stdin>", line
1
596 string.strip('str') 'ing'
598 SyntaxError: invalid syntax
601 Strings can be subscripted (indexed); like in C, the first character
602 of a string has subscript (index)
0. There is no separate character
603 type; a character is simply a string of size one. Like in Icon,
604 substrings can be specified with the
\emph{slice notation
}: two indices
605 separated by a colon.
616 Unlike a C string, Python strings cannot be changed. Assigning to an
617 indexed position in the string results in an error:
621 Traceback (most recent call last):
622 File "<stdin>", line
1, in ?
623 TypeError: object doesn't support item assignment
624 >>> word
[:
1] = 'Splat'
625 Traceback (most recent call last):
626 File "<stdin>", line
1, in ?
627 TypeError: object doesn't support slice assignment
630 However, creating a new string with the combined content is easy and
636 >>> 'Splat' + word
[4]
640 Slice indices have useful defaults; an omitted first index defaults to
641 zero, an omitted second index defaults to the size of the string being
645 >>> word
[:
2] # The first two characters
647 >>> word
[2:
] # All but the first two characters
651 Here's a useful invariant of slice operations:
652 \code{s
[:i
] + s
[i:
]} equals
\code{s
}.
655 >>> word
[:
2] + word
[2:
]
657 >>> word
[:
3] + word
[3:
]
661 Degenerate slice indices are handled gracefully: an index that is too
662 large is replaced by the string size, an upper bound smaller than the
663 lower bound returns an empty string.
674 Indices may be negative numbers, to start counting from the right.
678 >>> word
[-
1] # The last character
680 >>> word
[-
2] # The last-but-one character
682 >>> word
[-
2:
] # The last two characters
684 >>> word
[:-
2] # All but the last two characters
688 But note that -
0 is really the same as
0, so it does not count from
692 >>> word
[-
0] # (since -
0 equals
0)
696 Out-of-range negative slice indices are truncated, but don't try this
697 for single-element (non-slice) indices:
702 >>> word
[-
10] # error
703 Traceback (most recent call last):
704 File "<stdin>", line
1
705 IndexError: string index out of range
708 The best way to remember how slices work is to think of the indices as
709 pointing
\emph{between
} characters, with the left edge of the first
710 character numbered
0. Then the right edge of the last character of a
711 string of
\var{n
} characters has index
\var{n
}, for example:
714 +---+---+---+---+---+
715 | H | e | l | p | A |
716 +---+---+---+---+---+
721 The first row of numbers gives the position of the indices
0..
.5 in
722 the string; the second row gives the corresponding negative indices.
723 The slice from
\var{i
} to
\var{j
} consists of all characters between
724 the edges labeled
\var{i
} and
\var{j
}, respectively.
726 For non-negative indices, the length of a slice is the difference of
727 the indices, if both are within bounds, e.g., the length of
728 \code{word
[1:
3]} is
2.
730 The built-in function
\function{len()
} returns the length of a string:
733 >>> s = 'supercalifragilisticexpialidocious'
739 \subsection{Unicode Strings
\label{unicodeStrings
}}
740 \sectionauthor{Marc-Andre Lemburg
}{mal@lemburg.com
}
742 Starting with Python
2.0 a new data type for storing text data is
743 available to the programmer: the Unicode object. It can be used to
744 store and manipulate Unicode data (see
\url{http://www.unicode.org
})
745 and integrates well with the existing string objects providing
746 auto-conversions where necessary.
748 Unicode has the advantage of providing one ordinal for every character
749 in every script used in modern and ancient texts. Previously, there
750 were only
256 possible ordinals for script characters and texts were
751 typically bound to a code page which mapped the ordinals to script
752 characters. This lead to very much confusion especially with respect
753 to internationalization (usually written as
\samp{i18n
} ---
754 \character{i
} +
18 characters +
\character{n
}) of software. Unicode
755 solves these problems by defining one code page for all scripts.
757 Creating Unicode strings in Python is just as simple as creating
765 The small
\character{u
} in front of the quote indicates that an
766 Unicode string is supposed to be created. If you want to include
767 special characters in the string, you can do so by using the Python
768 \emph{Unicode-Escape
} encoding. The following example shows how:
771 >>> u'Hello
\u0020World !'
775 The escape sequence
\code{\e u0020
} indicates to insert the Unicode
776 character with the ordinal value
0x0020 (the space character) at the
779 Other characters are interpreted by using their respective ordinal
780 values directly as Unicode ordinals. If you have literal strings
781 in the standard Latin-
1 encoding that is used in many Western countries,
782 you will find it convenient that the lower
256 characters
783 of Unicode are the same as the
256 characters of Latin-
1.
785 For experts, there is also a raw mode just like the one for normal
786 strings. You have to prefix the opening quote with 'ur' to have
787 Python use the
\emph{Raw-Unicode-Escape
} encoding. It will only apply
788 the above
\code{\e uXXXX
} conversion if there is an uneven number of
789 backslashes in front of the small 'u'.
792 >>> ur'Hello
\u0020World !'
794 >>> ur'Hello\
\u0020World !'
795 u'Hello\\\
\u0020World !'
798 The raw mode is most useful when you have to enter lots of backslashes
799 e.g. in regular expressions.
801 Apart from these standard encodings, Python provides a whole set of
802 other ways of creating Unicode strings on the basis of a known
805 The built-in function
\function{unicode()
}\bifuncindex{unicode
} provides
806 access to all registered Unicode codecs (COders and DECoders). Some of
807 the more well known encodings which these codecs can convert are
808 \emph{Latin-
1},
\emph{ASCII
},
\emph{UTF-
8}, and
\emph{UTF-
16}.
809 The latter two are variable-length encodings that store each Unicode
810 character in one or more bytes. The default encoding is
811 normally set to ASCII, which passes through characters in the range
812 0 to
127 and rejects any other characters with an error.
813 When a Unicode string is printed, written to a file, or converted
814 with
\function{str()
}, conversion takes place using this default encoding.
824 Traceback (most recent call last):
825 File "<stdin>", line
1, in ?
826 UnicodeError: ASCII encoding error: ordinal not in range(
128)
829 To convert a Unicode string into an
8-bit string using a specific
830 encoding, Unicode objects provide an
\function{encode()
} method
831 that takes one argument, the name of the encoding. Lowercase names
832 for encodings are preferred.
835 >>> u"äöü".encode('utf-
8')
836 '
\xc3\xa4\xc3\xb6\xc3\xbc'
839 If you have data in a specific encoding and want to produce a
840 corresponding Unicode string from it, you can use the
841 \function{unicode()
} function with the encoding name as the second
845 >>> unicode('
\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-
8')
849 \subsection{Lists
\label{lists
}}
851 Python knows a number of
\emph{compound
} data types, used to group
852 together other values. The most versatile is the
\emph{list
}, which
853 can be written as a list of comma-separated values (items) between
854 square brackets. List items need not all have the same type.
857 >>> a =
['spam', 'eggs',
100,
1234]
859 ['spam', 'eggs',
100,
1234]
862 Like string indices, list indices start at
0, and lists can be sliced,
863 concatenated and so on:
874 >>> a
[:
2] +
['bacon',
2*
2]
875 ['spam', 'eggs', 'bacon',
4]
876 >>>
3*a
[:
3] +
['Boe!'
]
877 ['spam', 'eggs',
100, 'spam', 'eggs',
100, 'spam', 'eggs',
100, 'Boe!'
]
880 Unlike strings, which are
\emph{immutable
}, it is possible to change
881 individual elements of a list:
885 ['spam', 'eggs',
100,
1234]
888 ['spam', 'eggs',
123,
1234]
891 Assignment to slices is also possible, and this can even change the size
895 >>> # Replace some items:
904 ... a
[1:
1] =
['bletch', 'xyzzy'
]
906 [123, 'bletch', 'xyzzy',
1234]
907 >>> a
[:
0] = a # Insert (a copy of) itself at the beginning
909 [123, 'bletch', 'xyzzy',
1234,
123, 'bletch', 'xyzzy',
1234]
912 The built-in function
\function{len()
} also applies to lists:
919 It is possible to nest lists (create lists containing other lists),
931 >>> p
[1].append('xtra') # See section
5.1
933 [1,
[2,
3, 'xtra'
],
4]
938 Note that in the last example,
\code{p
[1]} and
\code{q
} really refer to
939 the same object! We'll come back to
\emph{object semantics
} later.
941 \section{First Steps Towards Programming
\label{firstSteps
}}
943 Of course, we can use Python for more complicated tasks than adding
944 two and two together. For instance, we can write an initial
945 subsequence of the
\emph{Fibonacci
} series as follows:
948 >>> # Fibonacci series:
949 ... # the sum of two elements defines the next
963 This example introduces several new features.
968 The first line contains a
\emph{multiple assignment
}: the variables
969 \code{a
} and
\code{b
} simultaneously get the new values
0 and
1. On the
970 last line this is used again, demonstrating that the expressions on
971 the right-hand side are all evaluated first before any of the
972 assignments take place. The right-hand side expressions are evaluated
973 from the left to the right.
976 The
\keyword{while
} loop executes as long as the condition (here:
977 \code{b <
10}) remains true. In Python, like in C, any non-zero
978 integer value is true; zero is false. The condition may also be a
979 string or list value, in fact any sequence; anything with a non-zero
980 length is true, empty sequences are false. The test used in the
981 example is a simple comparison. The standard comparison operators are
982 written the same as in C:
\code{<
} (less than),
\code{>
} (greater than),
983 \code{==
} (equal to),
\code{<=
} (less than or equal to),
984 \code{>=
} (greater than or equal to) and
\code{!=
} (not equal to).
987 The
\emph{body
} of the loop is
\emph{indented
}: indentation is Python's
988 way of grouping statements. Python does not (yet!) provide an
989 intelligent input line editing facility, so you have to type a tab or
990 space(s) for each indented line. In practice you will prepare more
991 complicated input for Python with a text editor; most text editors have
992 an auto-indent facility. When a compound statement is entered
993 interactively, it must be followed by a blank line to indicate
994 completion (since the parser cannot guess when you have typed the last
995 line). Note that each line within a basic block must be indented by
999 The
\keyword{print
} statement writes the value of the expression(s) it is
1000 given. It differs from just writing the expression you want to write
1001 (as we did earlier in the calculator examples) in the way it handles
1002 multiple expressions and strings. Strings are printed without quotes,
1003 and a space is inserted between items, so you can format things nicely,
1008 >>> print 'The value of i is', i
1009 The value of i is
65536
1012 A trailing comma avoids the newline after the output:
1020 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1023 Note that the interpreter inserts a newline before it prints the next
1024 prompt if the last line was not completed.
1029 \chapter{More Control Flow Tools
\label{moreControl
}}
1031 Besides the
\keyword{while
} statement just introduced, Python knows
1032 the usual control flow statements known from other languages, with
1035 \section{\keyword{if
} Statements
\label{if
}}
1037 Perhaps the most well-known statement type is the
1038 \keyword{if
} statement. For example:
1041 >>> x = int(raw_input("Please enter a number: "))
1044 ... print 'Negative changed to zero'
1054 There can be zero or more
\keyword{elif
} parts, and the
1055 \keyword{else
} part is optional. The keyword `
\keyword{elif
}' is
1056 short for `else if', and is useful to avoid excessive indentation. An
1057 \keyword{if
} \ldots\
\keyword{elif
} \ldots\
\keyword{elif
} \ldots\ sequence
1058 % Weird spacings happen here if the wrapping of the source text
1059 % gets changed in the wrong way.
1060 is a substitute for the
\keyword{switch
} or
1061 \keyword{case
} statements found in other languages.
1064 \section{\keyword{for
} Statements
\label{for
}}
1066 The
\keyword{for
}\stindex{for
} statement in Python differs a bit from
1067 what you may be used to in C or Pascal. Rather than always
1068 iterating over an arithmetic progression of numbers (like in Pascal),
1069 or giving the user the ability to define both the iteration step and
1070 halting condition (as C), Python's
1071 \keyword{for
}\stindex{for
} statement iterates over the items of any
1072 sequence (e.g., a list or a string), in the order that they appear in
1073 the sequence. For example (no pun intended):
1074 % One suggestion was to give a real C example here, but that may only
1075 % serve to confuse non-C programmers.
1078 >>> # Measure some strings:
1079 ... a =
['cat', 'window', 'defenestrate'
]
1088 It is not safe to modify the sequence being iterated over in the loop
1089 (this can only happen for mutable sequence types, i.e., lists). If
1090 you need to modify the list you are iterating over, e.g., duplicate
1091 selected items, you must iterate over a copy. The slice notation
1092 makes this particularly convenient:
1095 >>> for x in a
[:
]: # make a slice copy of the entire list
1096 ... if len(x) >
6: a.insert(
0, x)
1099 ['defenestrate', 'cat', 'window', 'defenestrate'
]
1103 \section{The
\function{range()
} Function
\label{range
}}
1105 If you do need to iterate over a sequence of numbers, the built-in
1106 function
\function{range()
} comes in handy. It generates lists
1107 containing arithmetic progressions, e.g.:
1111 [0,
1,
2,
3,
4,
5,
6,
7,
8,
9]
1114 The given end point is never part of the generated list;
1115 \code{range(
10)
} generates a list of
10 values, exactly the legal
1116 indices for items of a sequence of length
10. It is possible to let
1117 the range start at another number, or to specify a different increment
1118 (even negative; sometimes this is called the `step'):
1125 >>> range(-
10, -
100, -
30)
1129 To iterate over the indices of a sequence, combine
1130 \function{range()
} and
\function{len()
} as follows:
1133 >>> a =
['Mary', 'had', 'a', 'little', 'lamb'
]
1134 >>> for i in range(len(a)):
1145 \section{\keyword{break
} and
\keyword{continue
} Statements, and
1146 \keyword{else
} Clauses on Loops
1149 The
\keyword{break
} statement, like in C, breaks out of the smallest
1150 enclosing
\keyword{for
} or
\keyword{while
} loop.
1152 The
\keyword{continue
} statement, also borrowed from C, continues
1153 with the next iteration of the loop.
1155 Loop statements may have an
\code{else
} clause; it is executed when
1156 the loop terminates through exhaustion of the list (with
1157 \keyword{for
}) or when the condition becomes false (with
1158 \keyword{while
}), but not when the loop is terminated by a
1159 \keyword{break
} statement. This is exemplified by the following loop,
1160 which searches for prime numbers:
1163 >>> for n in range(
2,
10):
1164 ... for x in range(
2, n):
1166 ... print n, 'equals', x, '*', n/x
1169 ... print n, 'is a prime number'
1182 \section{\keyword{pass
} Statements
\label{pass
}}
1184 The
\keyword{pass
} statement does nothing.
1185 It can be used when a statement is required syntactically but the
1186 program requires no action.
1191 ... pass # Busy-wait for keyboard interrupt
1196 \section{Defining Functions
\label{functions
}}
1198 We can create a function that writes the Fibonacci series to an
1202 >>> def fib(n): # write Fibonacci series up to n
1203 ... "Print a Fibonacci series up to n"
1209 >>> # Now call the function we just defined:
1211 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
1214 The keyword
\keyword{def
} introduces a function
\emph{definition
}. It
1215 must be followed by the function name and the parenthesized list of
1216 formal parameters. The statements that form the body of the function
1217 start at the next line, and must be indented. The first statement of
1218 the function body can optionally be a string literal; this string
1219 literal is the function's
\index{documentation strings
}documentation
1220 string, or
\dfn{docstring
}.
\index{docstrings
}\index{strings, documentation
}
1222 There are tools which use docstrings to automatically produce online
1223 or printed documentation, or to let the user interactively browse
1224 through code; it's good practice to include docstrings in code that
1225 you write, so try to make a habit of it.
1227 The
\emph{execution
} of a function introduces a new symbol table used
1228 for the local variables of the function. More precisely, all variable
1229 assignments in a function store the value in the local symbol table;
1230 whereas variable references first look in the local symbol table, then
1231 in the global symbol table, and then in the table of built-in names.
1232 Thus, global variables cannot be directly assigned a value within a
1233 function (unless named in a
\keyword{global
} statement), although
1234 they may be referenced.
1236 The actual parameters (arguments) to a function call are introduced in
1237 the local symbol table of the called function when it is called; thus,
1238 arguments are passed using
\emph{call by value
} (where the
1239 \emph{value
} is always an object
\emph{reference
}, not the value of
1240 the object).
\footnote{
1241 Actually,
\emph{call by object reference
} would be a better
1242 description, since if a mutable object is passed, the caller
1243 will see any changes the callee makes to it (e.g., items
1244 inserted into a list).
1245 } When a function calls another function, a new local symbol table is
1246 created for that call.
1248 A function definition introduces the function name in the current
1249 symbol table. The value of the function name
1250 has a type that is recognized by the interpreter as a user-defined
1251 function. This value can be assigned to another name which can then
1252 also be used as a function. This serves as a general renaming
1257 <function object at
10042ed0>
1260 1 1 2 3 5 8 13 21 34 55 89
1263 You might object that
\code{fib
} is not a function but a procedure. In
1264 Python, like in C, procedures are just functions that don't return a
1265 value. In fact, technically speaking, procedures do return a value,
1266 albeit a rather boring one. This value is called
\code{None
} (it's a
1267 built-in name). Writing the value
\code{None
} is normally suppressed by
1268 the interpreter if it would be the only value written. You can see it
1269 if you really want to:
1276 It is simple to write a function that returns a list of the numbers of
1277 the Fibonacci series, instead of printing it:
1280 >>> def fib2(n): # return Fibonacci series up to n
1281 ... "Return a list containing the Fibonacci series up to n"
1285 ... result.append(b) # see below
1289 >>> f100 = fib2(
100) # call it
1290 >>> f100 # write the result
1291 [1,
1,
2,
3,
5,
8,
13,
21,
34,
55,
89]
1294 This example, as usual, demonstrates some new Python features:
1299 The
\keyword{return
} statement returns with a value from a function.
1300 \keyword{return
} without an expression argument returns
\code{None
}.
1301 Falling off the end of a procedure also returns
\code{None
}.
1304 The statement
\code{result.append(b)
} calls a
\emph{method
} of the list
1305 object
\code{result
}. A method is a function that `belongs' to an
1306 object and is named
\code{obj.methodname
}, where
\code{obj
} is some
1307 object (this may be an expression), and
\code{methodname
} is the name
1308 of a method that is defined by the object's type. Different types
1309 define different methods. Methods of different types may have the
1310 same name without causing ambiguity. (It is possible to define your
1311 own object types and methods, using
\emph{classes
}, as discussed later
1313 The method
\method{append()
} shown in the example, is defined for
1314 list objects; it adds a new element at the end of the list. In this
1315 example it is equivalent to
\samp{result = result +
[b
]}, but more
1320 \section{More on Defining Functions
\label{defining
}}
1322 It is also possible to define functions with a variable number of
1323 arguments. There are three forms, which can be combined.
1325 \subsection{Default Argument Values
\label{defaultArgs
}}
1327 The most useful form is to specify a default value for one or more
1328 arguments. This creates a function that can be called with fewer
1329 arguments than it is defined, e.g.
1332 def ask_ok(prompt, retries=
4, complaint='Yes or no, please!'):
1334 ok = raw_input(prompt)
1335 if ok in ('y', 'ye', 'yes'): return
1
1336 if ok in ('n', 'no', 'nop', 'nope'): return
0
1337 retries = retries -
1
1338 if retries <
0: raise IOError, 'refusenik user'
1342 This function can be called either like this:
1343 \code{ask_ok('Do you really want to quit?')
} or like this:
1344 \code{ask_ok('OK to overwrite the file?',
2)
}.
1346 The default values are evaluated at the point of function definition
1347 in the
\emph{defining
} scope, so that e.g.
1351 def f(arg = i): print arg
1356 will print
\code{5}.
1358 \strong{Important warning:
} The default value is evaluated only once.
1359 This makes a difference when the default is a mutable object such as a
1360 list or dictionary. For example, the following function accumulates
1361 the arguments passed to it on subsequent calls:
1380 If you don't want the default to be shared between subsequent calls,
1381 you can write the function like this instead:
1391 \subsection{Keyword Arguments
\label{keywordArgs
}}
1393 Functions can also be called using
1394 keyword arguments of the form
\samp{\var{keyword
} =
\var{value
}}. For
1395 instance, the following function:
1398 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1399 print "-- This parrot wouldn't", action,
1400 print "if you put", voltage, "Volts through it."
1401 print "-- Lovely plumage, the", type
1402 print "-- It's", state, "!"
1405 could be called in any of the following ways:
1409 parrot(action = 'VOOOOOM', voltage =
1000000)
1410 parrot('a thousand', state = 'pushing up the daisies')
1411 parrot('a million', 'bereft of life', 'jump')
1414 but the following calls would all be invalid:
1417 parrot() # required argument missing
1418 parrot(voltage=
5.0, 'dead') # non-keyword argument following keyword
1419 parrot(
110, voltage=
220) # duplicate value for argument
1420 parrot(actor='John Cleese') # unknown keyword
1423 In general, an argument list must have any positional arguments
1424 followed by any keyword arguments, where the keywords must be chosen
1425 from the formal parameter names. It's not important whether a formal
1426 parameter has a default value or not. No argument may receive a
1427 value more than once --- formal parameter names corresponding to
1428 positional arguments cannot be used as keywords in the same calls.
1429 Here's an example that fails due to this restriction:
1432 >>> def function(a):
1435 >>> function(
0, a=
0)
1436 Traceback (most recent call last):
1437 File "<stdin>", line
1, in ?
1438 TypeError: keyword parameter redefined
1441 When a final formal parameter of the form
\code{**
\var{name
}} is
1442 present, it receives a dictionary containing all keyword arguments
1443 whose keyword doesn't correspond to a formal parameter. This may be
1444 combined with a formal parameter of the form
1445 \code{*
\var{name
}} (described in the next subsection) which receives a
1446 tuple containing the positional arguments beyond the formal parameter
1447 list. (
\code{*
\var{name
}} must occur before
\code{**
\var{name
}}.)
1448 For example, if we define a function like this:
1451 def cheeseshop(kind, *arguments, **keywords):
1452 print "-- Do you have any", kind, '?'
1453 print "-- I'm sorry, we're all out of", kind
1454 for arg in arguments: print arg
1456 for kw in keywords.keys(): print kw, ':', keywords
[kw
]
1459 It could be called like this:
1462 cheeseshop('Limburger', "It's very runny, sir.",
1463 "It's really very, VERY runny, sir.",
1464 client='John Cleese',
1465 shopkeeper='Michael Palin',
1466 sketch='Cheese Shop Sketch')
1469 and of course it would print:
1472 -- Do you have any Limburger ?
1473 -- I'm sorry, we're all out of Limburger
1474 It's very runny, sir.
1475 It's really very, VERY runny, sir.
1476 ----------------------------------------
1477 client : John Cleese
1478 shopkeeper : Michael Palin
1479 sketch : Cheese Shop Sketch
1483 \subsection{Arbitrary Argument Lists
\label{arbitraryArgs
}}
1485 Finally, the least frequently used option is to specify that a
1486 function can be called with an arbitrary number of arguments. These
1487 arguments will be wrapped up in a tuple. Before the variable number
1488 of arguments, zero or more normal arguments may occur.
1491 def fprintf(file, format, *args):
1492 file.write(format
% args)
1496 \subsection{Lambda Forms
\label{lambda
}}
1498 By popular demand, a few features commonly found in functional
1499 programming languages and Lisp have been added to Python. With the
1500 \keyword{lambda
} keyword, small anonymous functions can be created.
1501 Here's a function that returns the sum of its two arguments:
1502 \samp{lambda a, b: a+b
}. Lambda forms can be used wherever function
1503 objects are required. They are syntactically restricted to a single
1504 expression. Semantically, they are just syntactic sugar for a normal
1505 function definition. Like nested function definitions, lambda forms
1506 cannot reference variables from the containing scope, but this can be
1507 overcome through the judicious use of default argument values, e.g.
1510 >>> def make_incrementor(n):
1511 ... return lambda x, incr=n: x+incr
1513 >>> f = make_incrementor(
42)
1522 \subsection{Documentation Strings
\label{docstrings
}}
1524 There are emerging conventions about the content and formatting of
1525 documentation strings.
1526 \index{docstrings
}\index{documentation strings
}
1527 \index{strings, documentation
}
1529 The first line should always be a short, concise summary of the
1530 object's purpose. For brevity, it should not explicitly state the
1531 object's name or type, since these are available by other means
1532 (except if the name happens to be a verb describing a function's
1533 operation). This line should begin with a capital letter and end with
1536 If there are more lines in the documentation string, the second line
1537 should be blank, visually separating the summary from the rest of the
1538 description. The following lines should be one or more paragraphs
1539 describing the object's calling conventions, its side effects, etc.
1541 The Python parser does not strip indentation from multi-line string
1542 literals in Python, so tools that process documentation have to strip
1543 indentation if desired. This is done using the following convention.
1544 The first non-blank line
\emph{after
} the first line of the string
1545 determines the amount of indentation for the entire documentation
1546 string. (We can't use the first line since it is generally adjacent
1547 to the string's opening quotes so its indentation is not apparent in
1548 the string literal.) Whitespace ``equivalent'' to this indentation is
1549 then stripped from the start of all lines of the string. Lines that
1550 are indented less should not occur, but if they occur all their
1551 leading whitespace should be stripped. Equivalence of whitespace
1552 should be tested after expansion of tabs (to
8 spaces, normally).
1554 Here is an example of a multi-line docstring:
1557 >>> def my_function():
1558 ... """Do nothing, but
document it.
1560 ... No, really, it doesn't do anything.
1564 >>> print my_function.__doc__
1565 Do nothing, but
document it.
1567 No, really, it doesn't do anything.
1573 \chapter{Data Structures
\label{structures
}}
1575 This chapter describes some things you've learned about already in
1576 more detail, and adds some new things as well.
1579 \section{More on Lists
\label{moreLists
}}
1581 The list data type has some more methods. Here are all of the methods
1586 \item[\code{append(x)
}]
1587 Add an item to the end of the list;
1588 equivalent to
\code{a
[len(a):
] =
[x
]}.
1590 \item[\code{extend(L)
}]
1591 Extend the list by appending all the items in the given list;
1592 equivalent to
\code{a
[len(a):
] = L
}.
1594 \item[\code{insert(i, x)
}]
1595 Insert an item at a given position. The first argument is the index of
1596 the element before which to insert, so
\code{a.insert(
0, x)
} inserts at
1597 the front of the list, and
\code{a.insert(len(a), x)
} is equivalent to
1600 \item[\code{remove(x)
}]
1601 Remove the first item from the list whose value is
\code{x
}.
1602 It is an error if there is no such item.
1604 \item[\code{pop(
\optional{i
})
}]
1605 Remove the item at the given position in the list, and return it. If
1606 no index is specified,
\code{a.pop()
} returns the last item in the
1607 list. The item is also removed from the list.
1609 \item[\code{index(x)
}]
1610 Return the index in the list of the first item whose value is
\code{x
}.
1611 It is an error if there is no such item.
1613 \item[\code{count(x)
}]
1614 Return the number of times
\code{x
} appears in the list.
1616 \item[\code{sort()
}]
1617 Sort the items of the list, in place.
1619 \item[\code{reverse()
}]
1620 Reverse the elements of the list, in place.
1624 An example that uses most of the list methods:
1627 >>> a =
[66.6,
333,
333,
1,
1234.5]
1628 >>> print a.count(
333), a.count(
66.6), a.count('x')
1633 [66.6,
333, -
1,
333,
1,
1234.5,
333]
1638 [66.6, -
1,
333,
1,
1234.5,
333]
1641 [333,
1234.5,
1,
333, -
1,
66.6]
1644 [-
1,
1,
66.6,
333,
333,
1234.5]
1648 \subsection{Using Lists as Stacks
\label{lists-as-stacks
}}
1649 \sectionauthor{Ka-Ping Yee
}{ping@lfw.org
}
1651 The list methods make it very easy to use a list as a stack, where the
1652 last element added is the first element retrieved (``last-in,
1653 first-out''). To add an item to the top of the stack, use
1654 \method{append()
}. To retrieve an item from the top of the stack, use
1655 \method{pop()
} without an explicit index. For example:
1658 >>> stack =
[3,
4,
5]
1676 \subsection{Using Lists as Queues
\label{lists-as-queues
}}
1677 \sectionauthor{Ka-Ping Yee
}{ping@lfw.org
}
1679 You can also use a list conveniently as a queue, where the first
1680 element added is the first element retrieved (``first-in,
1681 first-out''). To add an item to the back of the queue, use
1682 \method{append()
}. To retrieve an item from the front of the queue,
1683 use
\method{pop()
} with
\code{0} as the index. For example:
1686 >>> queue =
["Eric", "John", "Michael"
]
1687 >>> queue.append("Terry") # Terry arrives
1688 >>> queue.append("Graham") # Graham arrives
1694 ['Michael', 'Terry', 'Graham'
]
1698 \subsection{Functional Programming Tools
\label{functional
}}
1700 There are three built-in functions that are very useful when used with
1701 lists:
\function{filter()
},
\function{map()
}, and
\function{reduce()
}.
1703 \samp{filter(
\var{function
},
\var{sequence
})
} returns a sequence (of
1704 the same type, if possible) consisting of those items from the
1705 sequence for which
\code{\var{function
}(
\var{item
})
} is true. For
1706 example, to compute some primes:
1709 >>> def f(x): return x
% 2 != 0 and x % 3 != 0
1711 >>> filter(f, range(
2,
25))
1712 [5,
7,
11,
13,
17,
19,
23]
1715 \samp{map(
\var{function
},
\var{sequence
})
} calls
1716 \code{\var{function
}(
\var{item
})
} for each of the sequence's items and
1717 returns a list of the return values. For example, to compute some
1721 >>> def cube(x): return x*x*x
1723 >>> map(cube, range(
1,
11))
1724 [1,
8,
27,
64,
125,
216,
343,
512,
729,
1000]
1727 More than one sequence may be passed; the function must then have as
1728 many arguments as there are sequences and is called with the
1729 corresponding item from each sequence (or
\code{None
} if some sequence
1730 is shorter than another). If
\code{None
} is passed for the function,
1731 a function returning its argument(s) is substituted.
1733 Combining these two special cases, we see that
1734 \samp{map(None,
\var{list1
},
\var{list2
})
} is a convenient way of
1735 turning a pair of lists into a list of pairs. For example:
1739 >>> def square(x): return x*x
1741 >>> map(None, seq, map(square, seq))
1742 [(
0,
0), (
1,
1), (
2,
4), (
3,
9), (
4,
16), (
5,
25), (
6,
36), (
7,
49)
]
1745 \samp{reduce(
\var{func
},
\var{sequence
})
} returns a single value
1746 constructed by calling the binary function
\var{func
} on the first two
1747 items of the sequence, then on the result and the next item, and so
1748 on. For example, to compute the sum of the numbers
1 through
10:
1751 >>> def add(x,y): return x+y
1753 >>> reduce(add, range(
1,
11))
1757 If there's only one item in the sequence, its value is returned; if
1758 the sequence is empty, an exception is raised.
1760 A third argument can be passed to indicate the starting value. In this
1761 case the starting value is returned for an empty sequence, and the
1762 function is first applied to the starting value and the first sequence
1763 item, then to the result and the next item, and so on. For example,
1767 ... def add(x,y): return x+y
1768 ... return reduce(add, seq,
0)
1770 >>> sum(range(
1,
11))
1777 \subsection{List Comprehensions
}
1779 List comprehensions provide a concise way to create lists without resorting
1780 to use of
\function{map()
},
\function{filter()
} and/or
\keyword{lambda
}.
1781 The resulting list definition tends often to be clearer than lists built
1782 using those constructs. Each list comprehension consists of an expression
1783 following by a
\keyword{for
} clause, then zero or more
\keyword{for
} or
1784 \keyword{if
} clauses. The result will be a list resulting from evaluating
1785 the expression in the context of the
\keyword{for
} and
\keyword{if
} clauses
1786 which follow it. If the expression would evaluate to a tuple, it must be
1790 >>> freshfruit =
[' banana', ' loganberry ', 'passion fruit '
]
1791 >>>
[weapon.strip() for weapon in freshfruit
]
1792 ['banana', 'loganberry', 'passion fruit'
]
1794 >>>
[3*x for x in vec
]
1796 >>>
[3*x for x in vec if x >
3]
1798 >>>
[3*x for x in vec if x <
2]
1800 >>>
[{x: x**
2} for x in vec
]
1801 [{2:
4},
{4:
16},
{6:
36}]
1802 >>>
[[x,x**
2] for x in vec
]
1803 [[2,
4],
[4,
16],
[6,
36]]
1804 >>>
[x, x**
2 for x in vec
] # error - parens required for tuples
1805 File "<stdin>", line
1
1806 [x, x**
2 for x in vec
]
1808 SyntaxError: invalid syntax
1809 >>>
[(x, x**
2) for x in vec
]
1810 [(
2,
4), (
4,
16), (
6,
36)
]
1811 >>> vec1 =
[2,
4,
6]
1812 >>> vec2 =
[4,
3, -
9]
1813 >>>
[x*y for x in vec1 for y in vec2
]
1814 [8,
6, -
18,
16,
12, -
36,
24,
18, -
54]
1815 >>>
[x+y for x in vec1 for y in vec2
]
1816 [6,
5, -
7,
8,
7, -
5,
10,
9, -
3]
1820 \section{The
\keyword{del
} statement
\label{del
}}
1822 There is a way to remove an item from a list given its index instead
1823 of its value: the
\keyword{del
} statement. This can also be used to
1824 remove slices from a list (which we did earlier by assignment of an
1825 empty list to the slice). For example:
1829 [-
1,
1,
66.6,
333,
333,
1234.5]
1832 [1,
66.6,
333,
333,
1234.5]
1838 \keyword{del
} can also be used to delete entire variables:
1844 Referencing the name
\code{a
} hereafter is an error (at least until
1845 another value is assigned to it). We'll find other uses for
1846 \keyword{del
} later.
1849 \section{Tuples and Sequences
\label{tuples
}}
1851 We saw that lists and strings have many common properties, e.g.,
1852 indexing and slicing operations. They are two examples of
1853 \emph{sequence
} data types. Since Python is an evolving language,
1854 other sequence data types may be added. There is also another
1855 standard sequence data type: the
\emph{tuple
}.
1857 A tuple consists of a number of values separated by commas, for
1861 >>> t =
12345,
54321, 'hello!'
1865 (
12345,
54321, 'hello!')
1866 >>> # Tuples may be nested:
1867 ... u = t, (
1,
2,
3,
4,
5)
1869 ((
12345,
54321, 'hello!'), (
1,
2,
3,
4,
5))
1872 As you see, on output tuples are alway enclosed in parentheses, so
1873 that nested tuples are interpreted correctly; they may be input with
1874 or without surrounding parentheses, although often parentheses are
1875 necessary anyway (if the tuple is part of a larger expression).
1877 Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1878 from a database, etc. Tuples, like strings, are immutable: it is not
1879 possible to assign to the individual items of a tuple (you can
1880 simulate much of the same effect with slicing and concatenation,
1881 though). It is also possible to create tuples which contain mutable
1882 objects, such as lists.
1884 A special problem is the construction of tuples containing
0 or
1
1885 items: the syntax has some extra quirks to accommodate these. Empty
1886 tuples are constructed by an empty pair of parentheses; a tuple with
1887 one item is constructed by following a value with a comma
1888 (it is not sufficient to enclose a single value in parentheses).
1889 Ugly, but effective. For example:
1893 >>> singleton = 'hello', # <-- note trailing comma
1902 The statement
\code{t =
12345,
54321, 'hello!'
} is an example of
1903 \emph{tuple packing
}: the values
\code{12345},
\code{54321} and
1904 \code{'hello!'
} are packed together in a tuple. The reverse operation
1905 is also possible, e.g.:
1911 This is called, appropriately enough,
\emph{sequence unpacking
}.
1912 Sequence unpacking requires that the list of variables on the left
1913 have the same number of elements as the length of the sequence. Note
1914 that multiple assignment is really just a combination of tuple packing
1915 and sequence unpacking!
1917 There is a small bit of asymmetry here: packing multiple values
1918 always creates a tuple, and unpacking works for any sequence.
1920 % XXX Add a bit on the difference between tuples and lists.
1923 \section{Dictionaries
\label{dictionaries
}}
1925 Another useful data type built into Python is the
\emph{dictionary
}.
1926 Dictionaries are sometimes found in other languages as ``associative
1927 memories'' or ``associative arrays''. Unlike sequences, which are
1928 indexed by a range of numbers, dictionaries are indexed by
\emph{keys
},
1929 which can be any immutable type; strings and numbers can always be
1930 keys. Tuples can be used as keys if they contain only strings,
1931 numbers, or tuples; if a tuple contains any mutable object either
1932 directly or indirectly, it cannot be used as a key. You can't use
1933 lists as keys, since lists can be modified in place using their
1934 \method{append()
} and
\method{extend()
} methods, as well as slice and
1935 indexed assignments.
1937 It is best to think of a dictionary as an unordered set of
1938 \emph{key: value
} pairs, with the requirement that the keys are unique
1939 (within one dictionary).
1940 A pair of braces creates an empty dictionary:
\code{\
{\
}}.
1941 Placing a comma-separated list of key:value pairs within the
1942 braces adds initial key:value pairs to the dictionary; this is also the
1943 way dictionaries are written on output.
1945 The main operations on a dictionary are storing a value with some key
1946 and extracting the value given the key. It is also possible to delete
1949 If you store using a key that is already in use, the old value
1950 associated with that key is forgotten. It is an error to extract a
1951 value using a non-existent key.
1953 The
\code{keys()
} method of a dictionary object returns a list of all
1954 the keys used in the dictionary, in random order (if you want it
1955 sorted, just apply the
\code{sort()
} method to the list of keys). To
1956 check whether a single key is in the dictionary, use the
1957 \code{has_key()
} method of the dictionary.
1959 Here is a small example using a dictionary:
1962 >>> tel =
{'jack':
4098, 'sape':
4139}
1963 >>> tel
['guido'
] =
4127
1965 {'sape':
4139, 'guido':
4127, 'jack':
4098}
1969 >>> tel
['irv'
] =
4127
1971 {'guido':
4127, 'irv':
4127, 'jack':
4098}
1973 ['guido', 'irv', 'jack'
]
1974 >>> tel.has_key('guido')
1978 \section{More on Conditions
\label{conditions
}}
1980 The conditions used in
\code{while
} and
\code{if
} statements above can
1981 contain other operators besides comparisons.
1983 The comparison operators
\code{in
} and
\code{not in
} check whether a value
1984 occurs (does not occur) in a sequence. The operators
\code{is
} and
1985 \code{is not
} compare whether two objects are really the same object; this
1986 only matters for mutable objects like lists. All comparison operators
1987 have the same priority, which is lower than that of all numerical
1990 Comparisons can be chained: e.g.,
\code{a < b == c
} tests whether
1991 \code{a
} is less than
\code{b
} and moreover
\code{b
} equals
\code{c
}.
1993 Comparisons may be combined by the Boolean operators
\code{and
} and
1994 \code{or
}, and the outcome of a comparison (or of any other Boolean
1995 expression) may be negated with
\code{not
}. These all have lower
1996 priorities than comparison operators again; between them,
\code{not
} has
1997 the highest priority, and
\code{or
} the lowest, so that
1998 \code{A and not B or C
} is equivalent to
\code{(A and (not B)) or C
}. Of
1999 course, parentheses can be used to express the desired composition.
2001 The Boolean operators
\code{and
} and
\code{or
} are so-called
2002 \emph{shortcut
} operators: their arguments are evaluated from left to
2003 right, and evaluation stops as soon as the outcome is determined.
2004 E.g., if
\code{A
} and
\code{C
} are true but
\code{B
} is false,
\code{A
2005 and B and C
} does not evaluate the expression C. In general, the
2006 return value of a shortcut operator, when used as a general value and
2007 not as a Boolean, is the last evaluated argument.
2009 It is possible to assign the result of a comparison or other Boolean
2010 expression to a variable. For example,
2013 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
2014 >>> non_null = string1 or string2 or string3
2019 Note that in Python, unlike C, assignment cannot occur inside expressions.
2020 C programmers may grumble about this, but it avoids a common class of
2021 problems encountered in C programs: typing
\code{=
} in an expression when
2022 \code{==
} was intended.
2025 \section{Comparing Sequences and Other Types
\label{comparing
}}
2027 Sequence objects may be compared to other objects with the same
2028 sequence type. The comparison uses
\emph{lexicographical
} ordering:
2029 first the first two items are compared, and if they differ this
2030 determines the outcome of the comparison; if they are equal, the next
2031 two items are compared, and so on, until either sequence is exhausted.
2032 If two items to be compared are themselves sequences of the same type,
2033 the lexicographical comparison is carried out recursively. If all
2034 items of two sequences compare equal, the sequences are considered
2035 equal. If one sequence is an initial subsequence of the other, the
2036 shorter sequence is the smaller one. Lexicographical ordering for
2037 strings uses the
\ASCII{} ordering for individual characters. Some
2038 examples of comparisons between sequences with the same types:
2041 (
1,
2,
3) < (
1,
2,
4)
2042 [1,
2,
3] <
[1,
2,
4]
2043 'ABC' < 'C' < 'Pascal' < 'Python'
2044 (
1,
2,
3,
4) < (
1,
2,
4)
2046 (
1,
2,
3) == (
1.0,
2.0,
3.0)
2047 (
1,
2, ('aa', 'ab')) < (
1,
2, ('abc', 'a'),
4)
2050 Note that comparing objects of different types is legal. The outcome
2051 is deterministic but arbitrary: the types are ordered by their name.
2052 Thus, a list is always smaller than a string, a string is always
2053 smaller than a tuple, etc. Mixed numeric types are compared according
2054 to their numeric value, so
0 equals
0.0, etc.
\footnote{
2055 The rules for comparing objects of different types should
2056 not be relied upon; they may change in a future version of
2061 \chapter{Modules
\label{modules
}}
2063 If you quit from the Python interpreter and enter it again, the
2064 definitions you have made (functions and variables) are lost.
2065 Therefore, if you want to write a somewhat longer program, you are
2066 better off using a text editor to prepare the input for the interpreter
2067 and running it with that file as input instead. This is known as creating a
2068 \emph{script
}. As your program gets longer, you may want to split it
2069 into several files for easier maintenance. You may also want to use a
2070 handy function that you've written in several programs without copying
2071 its definition into each program.
2073 To support this, Python has a way to put definitions in a file and use
2074 them in a script or in an interactive instance of the interpreter.
2075 Such a file is called a
\emph{module
}; definitions from a module can be
2076 \emph{imported
} into other modules or into the
\emph{main
} module (the
2077 collection of variables that you have access to in a script
2078 executed at the top level
2079 and in calculator mode).
2081 A module is a file containing Python definitions and statements. The
2082 file name is the module name with the suffix
\file{.py
} appended. Within
2083 a module, the module's name (as a string) is available as the value of
2084 the global variable
\code{__name__
}. For instance, use your favorite text
2085 editor to create a file called
\file{fibo.py
} in the current directory
2086 with the following contents:
2089 # Fibonacci numbers module
2091 def fib(n): # write Fibonacci series up to n
2097 def fib2(n): # return Fibonacci series up to n
2106 Now enter the Python interpreter and import this module with the
2113 This does not enter the names of the functions defined in
\code{fibo
}
2114 directly in the current symbol table; it only enters the module name
2116 Using the module name you can access the functions:
2120 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
2122 [1,
1,
2,
3,
5,
8,
13,
21,
34,
55,
89]
2127 If you intend to use a function often you can assign it to a local name:
2132 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2136 \section{More on Modules
\label{moreModules
}}
2138 A module can contain executable statements as well as function
2140 These statements are intended to initialize the module.
2141 They are executed only the
2142 \emph{first
} time the module is imported somewhere.
\footnote{
2143 In fact function definitions are also `statements' that are
2144 `executed'; the execution enters the function name in the
2145 module's global symbol table.
2148 Each module has its own private symbol table, which is used as the
2149 global symbol table by all functions defined in the module.
2150 Thus, the author of a module can use global variables in the module
2151 without worrying about accidental clashes with a user's global
2153 On the other hand, if you know what you are doing you can touch a
2154 module's global variables with the same notation used to refer to its
2156 \code{modname.itemname
}.
2158 Modules can import other modules. It is customary but not required to
2159 place all
\keyword{import
} statements at the beginning of a module (or
2160 script, for that matter). The imported module names are placed in the
2161 importing module's global symbol table.
2163 There is a variant of the
\keyword{import
} statement that imports
2164 names from a module directly into the importing module's symbol
2168 >>> from fibo import fib, fib2
2170 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2173 This does not introduce the module name from which the imports are taken
2174 in the local symbol table (so in the example,
\code{fibo
} is not
2177 There is even a variant to import all names that a module defines:
2180 >>> from fibo import *
2182 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2185 This imports all names except those beginning with an underscore
2189 \subsection{The Module Search Path
\label{searchPath
}}
2191 \indexiii{module
}{search
}{path
}
2192 When a module named
\module{spam
} is imported, the interpreter searches
2193 for a file named
\file{spam.py
} in the current directory,
2194 and then in the list of directories specified by
2195 the environment variable
\envvar{PYTHONPATH
}. This has the same syntax as
2196 the shell variable
\envvar{PATH
}, i.e., a list of
2197 directory names. When
\envvar{PYTHONPATH
} is not set, or when the file
2198 is not found there, the search continues in an installation-dependent
2199 default path; on
\UNIX{}, this is usually
\file{.:/usr/local/lib/python
}.
2201 Actually, modules are searched in the list of directories given by the
2202 variable
\code{sys.path
} which is initialized from the directory
2203 containing the input script (or the current directory),
2204 \envvar{PYTHONPATH
} and the installation-dependent default. This allows
2205 Python programs that know what they're doing to modify or replace the
2206 module search path. See the section on Standard Modules later.
2208 \subsection{``Compiled'' Python files
}
2210 As an important speed-up of the start-up time for short programs that
2211 use a lot of standard modules, if a file called
\file{spam.pyc
} exists
2212 in the directory where
\file{spam.py
} is found, this is assumed to
2213 contain an already-``byte-compiled'' version of the module
\module{spam
}.
2214 The modification time of the version of
\file{spam.py
} used to create
2215 \file{spam.pyc
} is recorded in
\file{spam.pyc
}, and the
2216 \file{.pyc
} file is ignored if these don't match.
2218 Normally, you don't need to do anything to create the
2219 \file{spam.pyc
} file. Whenever
\file{spam.py
} is successfully
2220 compiled, an attempt is made to write the compiled version to
2221 \file{spam.pyc
}. It is not an error if this attempt fails; if for any
2222 reason the file is not written completely, the resulting
2223 \file{spam.pyc
} file will be recognized as invalid and thus ignored
2224 later. The contents of the
\file{spam.pyc
} file are platform
2225 independent, so a Python module directory can be shared by machines of
2226 different architectures.
2228 Some tips for experts:
2233 When the Python interpreter is invoked with the
\programopt{-O
} flag,
2234 optimized code is generated and stored in
\file{.pyo
} files.
2235 The optimizer currently doesn't help much; it only removes
2236 \keyword{assert
} statements and
\code{SET_LINENO
} instructions.
2237 When
\programopt{-O
} is used,
\emph{all
} bytecode is optimized;
2238 \code{.pyc
} files are ignored and
\code{.py
} files are compiled to
2242 Passing two
\programopt{-O
} flags to the Python interpreter
2243 (
\programopt{-OO
}) will cause the bytecode compiler to perform
2244 optimizations that could in some rare cases result in malfunctioning
2245 programs. Currently only
\code{__doc__
} strings are removed from the
2246 bytecode, resulting in more compact
\file{.pyo
} files. Since some
2247 programs may rely on having these available, you should only use this
2248 option if you know what you're doing.
2251 A program doesn't run any faster when it is read from a
\file{.pyc
} or
2252 \file{.pyo
} file than when it is read from a
\file{.py
} file; the only
2253 thing that's faster about
\file{.pyc
} or
\file{.pyo
} files is the
2254 speed with which they are loaded.
2257 When a script is run by giving its name on the command line, the
2258 bytecode for the script is never written to a
\file{.pyc
} or
2259 \file{.pyo
} file. Thus, the startup time of a script may be reduced
2260 by moving most of its code to a module and having a small bootstrap
2261 script that imports that module. It is also possible to name a
2262 \file{.pyc
} or
\file{.pyo
} file directly on the command line.
2265 It is possible to have a file called
\file{spam.pyc
} (or
2266 \file{spam.pyo
} when
\programopt{-O
} is used) without a file
2267 \file{spam.py
} for the same module. This can be used to distribute a
2268 library of Python code in a form that is moderately hard to reverse
2272 The module
\module{compileall
}\refstmodindex{compileall
} can create
2273 \file{.pyc
} files (or
\file{.pyo
} files when
\programopt{-O
} is used) for
2274 all modules in a directory.
2279 \section{Standard Modules
\label{standardModules
}}
2281 Python comes with a library of standard modules, described in a separate
2282 document, the
\citetitle[../lib/lib.html
]{Python Library Reference
}
2283 (``Library Reference'' hereafter). Some modules are built into the
2284 interpreter; these provide access to operations that are not part of
2285 the core of the language but are nevertheless built in, either for
2286 efficiency or to provide access to operating system primitives such as
2287 system calls. The set of such modules is a configuration option; e.g.,
2288 the
\module{amoeba
} module is only provided on systems that somehow
2289 support Amoeba primitives. One particular module deserves some
2290 attention:
\module{sys
}\refstmodindex{sys
}, which is built into every
2291 Python interpreter. The variables
\code{sys.ps1
} and
2292 \code{sys.ps2
} define the strings used as primary and secondary
2307 These two variables are only defined if the interpreter is in
2310 The variable
\code{sys.path
} is a list of strings that determine the
2311 interpreter's search path for modules. It is initialized to a default
2312 path taken from the environment variable
\envvar{PYTHONPATH
}, or from
2313 a built-in default if
\envvar{PYTHONPATH
} is not set. You can modify
2314 it using standard list operations, e.g.:
2318 >>> sys.path.append('/ufs/guido/lib/python')
2321 \section{The
\function{dir()
} Function
\label{dir
}}
2323 The built-in function
\function{dir()
} is used to find out which names
2324 a module defines. It returns a sorted list of strings:
2327 >>> import fibo, sys
2329 ['__name__', 'fib', 'fib2'
]
2331 ['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
2332 'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
2333 'stderr', 'stdin', 'stdout', 'version'
]
2336 Without arguments,
\function{dir()
} lists the names you have defined
2340 >>> a =
[1,
2,
3,
4,
5]
2341 >>> import fibo, sys
2344 ['__name__', 'a', 'fib', 'fibo', 'sys'
]
2347 Note that it lists all types of names: variables, modules, functions, etc.
2349 \function{dir()
} does not list the names of built-in functions and
2350 variables. If you want a list of those, they are defined in the
2351 standard module
\module{__builtin__
}\refbimodindex{__builtin__
}:
2354 >>> import __builtin__
2355 >>> dir(__builtin__)
2356 ['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
2357 'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2358 'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
2359 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
2360 'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
2361 'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
2362 'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
2363 'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
2364 'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange'
]
2368 \section{Packages
\label{packages
}}
2370 Packages are a way of structuring Python's module namespace
2371 by using ``dotted module names''. For example, the module name
2372 \module{A.B
} designates a submodule named
\samp{B
} in a package named
2373 \samp{A
}. Just like the use of modules saves the authors of different
2374 modules from having to worry about each other's global variable names,
2375 the use of dotted module names saves the authors of multi-module
2376 packages like NumPy or the Python Imaging Library from having to worry
2377 about each other's module names.
2379 Suppose you want to design a collection of modules (a ``package'') for
2380 the uniform handling of sound files and sound data. There are many
2381 different sound file formats (usually recognized by their extension,
2382 e.g.
\file{.wav
},
\file{.aiff
},
\file{.au
}), so you may need to create
2383 and maintain a growing collection of modules for the conversion
2384 between the various file formats. There are also many different
2385 operations you might want to perform on sound data (e.g. mixing,
2386 adding echo, applying an equalizer function, creating an artificial
2387 stereo effect), so in addition you will be writing a never-ending
2388 stream of modules to perform these operations. Here's a possible
2389 structure for your package (expressed in terms of a hierarchical
2393 Sound/ Top-level package
2394 __init__.py Initialize the sound package
2395 Formats/ Subpackage for file format conversions
2404 Effects/ Subpackage for sound effects
2410 Filters/ Subpackage for filters
2418 The
\file{__init__.py
} files are required to make Python treat the
2419 directories as containing packages; this is done to prevent
2420 directories with a common name, such as
\samp{string
}, from
2421 unintentionally hiding valid modules that occur later on the module
2422 search path. In the simplest case,
\file{__init__.py
} can just be an
2423 empty file, but it can also execute initialization code for the
2424 package or set the
\code{__all__
} variable, described later.
2426 Users of the package can import individual modules from the
2427 package, for example:
2430 import Sound.Effects.echo
2433 This loads the submodule
\module{Sound.Effects.echo
}. It must be referenced
2434 with its full name, e.g.
2437 Sound.Effects.echo.echofilter(input, output, delay=
0.7, atten=
4)
2440 An alternative way of importing the submodule is:
2443 from Sound.Effects import echo
2446 This also loads the submodule
\module{echo
}, and makes it available without
2447 its package prefix, so it can be used as follows:
2450 echo.echofilter(input, output, delay=
0.7, atten=
4)
2453 Yet another variation is to import the desired function or variable directly:
2456 from Sound.Effects.echo import echofilter
2459 Again, this loads the submodule
\module{echo
}, but this makes its function
2460 \function{echofilter()
} directly available:
2463 echofilter(input, output, delay=
0.7, atten=
4)
2466 Note that when using
\code{from
\var{package
} import
\var{item
}}, the
2467 item can be either a submodule (or subpackage) of the package, or some
2468 other name defined in the package, like a function, class or
2469 variable. The
\code{import
} statement first tests whether the item is
2470 defined in the package; if not, it assumes it is a module and attempts
2471 to load it. If it fails to find it, an
2472 \exception{ImportError
} exception is raised.
2474 Contrarily, when using syntax like
\code{import
2475 \var{item.subitem.subsubitem
}}, each item except for the last must be
2476 a package; the last item can be a module or a package but can't be a
2477 class or function or variable defined in the previous item.
2479 \subsection{Importing * From a Package
\label{pkg-import-star
}}
2480 %The \code{__all__} Attribute
2482 Now what happens when the user writes
\code{from Sound.Effects import
2483 *
}? Ideally, one would hope that this somehow goes out to the
2484 filesystem, finds which submodules are present in the package, and
2485 imports them all. Unfortunately, this operation does not work very
2486 well on Mac and Windows platforms, where the filesystem does not
2487 always have accurate information about the case of a filename! On
2488 these platforms, there is no guaranteed way to know whether a file
2489 \file{ECHO.PY
} should be imported as a module
\module{echo
},
2490 \module{Echo
} or
\module{ECHO
}. (For example, Windows
95 has the
2491 annoying practice of showing all file names with a capitalized first
2492 letter.) The DOS
8+
3 filename restriction adds another interesting
2493 problem for long module names.
2495 The only solution is for the package author to provide an explicit
2496 index of the package. The import statement uses the following
2497 convention: if a package's
\file{__init__.py
} code defines a list
2498 named
\code{__all__
}, it is taken to be the list of module names that
2499 should be imported when
\code{from
\var{package
} import *
} is
2500 encountered. It is up to the package author to keep this list
2501 up-to-date when a new version of the package is released. Package
2502 authors may also decide not to support it, if they don't see a use for
2503 importing * from their package. For example, the file
2504 \file{Sounds/Effects/__init__.py
} could contain the following code:
2507 __all__ =
["echo", "surround", "reverse"
]
2510 This would mean that
\code{from Sound.Effects import *
} would
2511 import the three named submodules of the
\module{Sound
} package.
2513 If
\code{__all__
} is not defined, the statement
\code{from Sound.Effects
2514 import *
} does
\emph{not
} import all submodules from the package
2515 \module{Sound.Effects
} into the current namespace; it only ensures that the
2516 package
\module{Sound.Effects
} has been imported (possibly running its
2517 initialization code,
\file{__init__.py
}) and then imports whatever names are
2518 defined in the package. This includes any names defined (and
2519 submodules explicitly loaded) by
\file{__init__.py
}. It also includes any
2520 submodules of the package that were explicitly loaded by previous
2521 import statements, e.g.
2524 import Sound.Effects.echo
2525 import Sound.Effects.surround
2526 from Sound.Effects import *
2529 In this example, the echo and surround modules are imported in the
2530 current namespace because they are defined in the
2531 \module{Sound.Effects
} package when the
\code{from...import
} statement
2532 is executed. (This also works when
\code{__all__
} is defined.)
2534 Note that in general the practicing of importing * from a module or
2535 package is frowned upon, since it often causes poorly readable code.
2536 However, it is okay to use it to save typing in interactive sessions,
2537 and certain modules are designed to export only names that follow
2540 Remember, there is nothing wrong with using
\code{from Package
2541 import specific_submodule
}! In fact, this is the
2542 recommended notation unless the importing module needs to use
2543 submodules with the same name from different packages.
2546 \subsection{Intra-package References
}
2548 The submodules often need to refer to each other. For example, the
2549 \module{surround
} module might use the
\module{echo
} module. In fact, such references
2550 are so common that the
\code{import
} statement first looks in the
2551 containing package before looking in the standard module search path.
2552 Thus, the surround module can simply use
\code{import echo
} or
2553 \code{from echo import echofilter
}. If the imported module is not
2554 found in the current package (the package of which the current module
2555 is a submodule), the
\code{import
} statement looks for a top-level module
2556 with the given name.
2558 When packages are structured into subpackages (as with the
2559 \module{Sound
} package in the example), there's no shortcut to refer
2560 to submodules of sibling packages - the full name of the subpackage
2561 must be used. For example, if the module
2562 \module{Sound.Filters.vocoder
} needs to use the
\module{echo
} module
2563 in the
\module{Sound.Effects
} package, it can use
\code{from
2564 Sound.Effects import echo
}.
2566 %(One could design a notation to refer to parent packages, similar to
2567 %the use of ".." to refer to the parent directory in Unix and Windows
2568 %filesystems. In fact, the \module{ni} module, which was the
2569 %ancestor of this package system, supported this using \code{__} for
2570 %the package containing the current module,
2571 %\code{__.__} for the parent package, and so on. This feature was dropped
2572 %because of its awkwardness; since most packages will have a relative
2573 %shallow substructure, this is no big loss.)
2577 \chapter{Input and Output
\label{io
}}
2579 There are several ways to present the output of a program; data can be
2580 printed in a human-readable form, or written to a file for future use.
2581 This chapter will discuss some of the possibilities.
2584 \section{Fancier Output Formatting
\label{formatting
}}
2586 So far we've encountered two ways of writing values:
\emph{expression
2587 statements
} and the
\keyword{print
} statement. (A third way is using
2588 the
\method{write()
} method of file objects; the standard output file
2589 can be referenced as
\code{sys.stdout
}. See the Library Reference for
2590 more information on this.)
2592 Often you'll want more control over the formatting of your output than
2593 simply printing space-separated values. There are two ways to format
2594 your output; the first way is to do all the string handling yourself;
2595 using string slicing and concatenation operations you can create any
2596 lay-out you can imagine. The standard module
2597 \module{string
}\refstmodindex{string
} contains some useful operations
2598 for padding strings to a given column width; these will be discussed
2599 shortly. The second way is to use the
\code{\%
} operator with a
2600 string as the left argument. The
\code{\%
} operator interprets the
2601 left argument much like a
\cfunction{sprintf()
}-style format
2602 string to be applied to the right argument, and returns the string
2603 resulting from this formatting operation.
2605 One question remains, of course: how do you convert values to strings?
2606 Luckily, Python has a way to convert any value to a string: pass it to
2607 the
\function{repr()
} function, or just write the value between
2608 reverse quotes (
\code{``
}). Some examples:
2613 >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
2615 The value of x is
31.4, and y is
40000...
2616 >>> # Reverse quotes work on other types besides numbers:
2620 '
[31.400000000000002,
40000]'
2621 >>> # Converting a string adds string quotes and backslashes:
2622 ... hello = 'hello, world
\n'
2623 >>> hellos = `hello`
2626 >>> # The argument of reverse quotes may be a tuple:
2627 ... `x, y, ('spam', 'eggs')`
2628 "(
31.400000000000002,
40000, ('spam', 'eggs'))"
2631 Here are two ways to write a table of squares and cubes:
2635 >>> for x in range(
1,
11):
2636 ... print string.rjust(`x`,
2), string.rjust(`x*x`,
3),
2637 ... # Note trailing comma on previous line
2638 ... print string.rjust(`x*x*x`,
4)
2650 >>> for x in range(
1,
11):
2651 ... print '
%2d %3d %4d' % (x, x*x, x*x*x)
2665 (Note that one space between each column was added by the way
2666 \keyword{print
} works: it always adds spaces between its arguments.)
2668 This example demonstrates the function
\function{string.rjust()
},
2669 which right-justifies a string in a field of a given width by padding
2670 it with spaces on the left. There are similar functions
2671 \function{string.ljust()
} and
\function{string.center()
}. These
2672 functions do not write anything, they just return a new string. If
2673 the input string is too long, they don't truncate it, but return it
2674 unchanged; this will mess up your column lay-out but that's usually
2675 better than the alternative, which would be lying about a value. (If
2676 you really want truncation you can always add a slice operation, as in
2677 \samp{string.ljust(x,~n)
[0:n
]}.)
2679 There is another function,
\function{string.zfill()
}, which pads a
2680 numeric string on the left with zeros. It understands about plus and
2685 >>> string.zfill('
12',
5)
2687 >>> string.zfill('-
3.14',
7)
2689 >>> string.zfill('
3.14159265359',
5)
2693 Using the
\code{\%
} operator looks like this:
2697 >>> print 'The value of PI is approximately
%5.3f.' % math.pi
2698 The value of PI is approximately
3.142.
2701 If there is more than one format in the string you pass a tuple as
2705 >>> table =
{'Sjoerd':
4127, 'Jack':
4098, 'Dcab':
7678}
2706 >>> for name, phone in table.items():
2707 ... print '
%-10s ==> %10d' % (name, phone)
2714 Most formats work exactly as in C and require that you pass the proper
2715 type; however, if you don't you get an exception, not a core dump.
2716 The
\code{\%s
} format is more relaxed: if the corresponding argument is
2717 not a string object, it is converted to string using the
2718 \function{str()
} built-in function. Using
\code{*
} to pass the width
2719 or precision in as a separate (integer) argument is supported. The
2720 C formats
\code{\%n
} and
\code{\%p
} are not supported.
2722 If you have a really long format string that you don't want to split
2723 up, it would be nice if you could reference the variables to be
2724 formatted by name instead of by position. This can be done by using
2725 an extension of C formats using the form
\code{\%(name)format
}, e.g.
2728 >>> table =
{'Sjoerd':
4127, 'Jack':
4098, 'Dcab':
8637678}
2729 >>> print 'Jack:
%(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2730 Jack:
4098; Sjoerd:
4127; Dcab:
8637678
2733 This is particularly useful in combination with the new built-in
2734 \function{vars()
} function, which returns a dictionary containing all
2737 \section{Reading and Writing Files
\label{files
}}
2740 \function{open()
}\bifuncindex{open
} returns a file
2741 object
\obindex{file
}, and is most commonly used with two arguments:
2742 \samp{open(
\var{filename
},
\var{mode
})
}.
2745 >>> f=open('/tmp/workfile', 'w')
2747 <open file '/tmp/workfile', mode 'w' at
80a0960>
2750 The first argument is a string containing the filename. The second
2751 argument is another string containing a few characters describing the
2752 way in which the file will be used.
\var{mode
} can be
\code{'r'
} when
2753 the file will only be read,
\code{'w'
} for only writing (an existing
2754 file with the same name will be erased), and
\code{'a'
} opens the file
2755 for appending; any data written to the file is automatically added to
2756 the end.
\code{'r+'
} opens the file for both reading and writing.
2757 The
\var{mode
} argument is optional;
\code{'r'
} will be assumed if
2760 On Windows and the Macintosh,
\code{'b'
} appended to the
2761 mode opens the file in binary mode, so there are also modes like
2762 \code{'rb'
},
\code{'wb'
}, and
\code{'r+b'
}. Windows makes a
2763 distinction between text and binary files; the end-of-line characters
2764 in text files are automatically altered slightly when data is read or
2765 written. This behind-the-scenes modification to file data is fine for
2766 \ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2767 \file{.EXE
} files. Be very careful to use binary mode when reading and
2768 writing such files. (Note that the precise semantics of text mode on
2769 the Macintosh depends on the underlying C library being used.)
2771 \subsection{Methods of File Objects
\label{fileMethods
}}
2773 The rest of the examples in this section will assume that a file
2774 object called
\code{f
} has already been created.
2776 To read a file's contents, call
\code{f.read(
\var{size
})
}, which reads
2777 some quantity of data and returns it as a string.
\var{size
} is an
2778 optional numeric argument. When
\var{size
} is omitted or negative,
2779 the entire contents of the file will be read and returned; it's your
2780 problem if the file is twice as large as your machine's memory.
2781 Otherwise, at most
\var{size
} bytes are read and returned. If the end
2782 of the file has been reached,
\code{f.read()
} will return an empty
2783 string (
\code {""
}).
2786 'This is the entire file.
\012'
2791 \code{f.readline()
} reads a single line from the file; a newline
2792 character (
\code{\e n
}) is left at the end of the string, and is only
2793 omitted on the last line of the file if the file doesn't end in a
2794 newline. This makes the return value unambiguous; if
2795 \code{f.readline()
} returns an empty string, the end of the file has
2796 been reached, while a blank line is represented by
\code{'
\e n'
}, a
2797 string containing only a single newline.
2801 'This is the first line of the file.
\012'
2803 'Second line of the file
\012'
2808 \code{f.readlines()
} returns a list containing all the lines of data
2809 in the file. If given an optional parameter
\var{sizehint
}, it reads
2810 that many bytes from the file and enough more to complete a line, and
2811 returns the lines from that. This is often used to allow efficient
2812 reading of a large file by lines, but without having to load the
2813 entire file in memory. Only complete lines will be returned.
2817 ['This is the first line of the file.
\012', 'Second line of the file
\012'
]
2820 \code{f.write(
\var{string
})
} writes the contents of
\var{string
} to
2821 the file, returning
\code{None
}.
2824 >>> f.write('This is a test
\n')
2827 \code{f.tell()
} returns an integer giving the file object's current
2828 position in the file, measured in bytes from the beginning of the
2829 file. To change the file object's position, use
2830 \samp{f.seek(
\var{offset
},
\var{from_what
})
}. The position is
2831 computed from adding
\var{offset
} to a reference point; the reference
2832 point is selected by the
\var{from_what
} argument. A
2833 \var{from_what
} value of
0 measures from the beginning of the file,
1
2834 uses the current file position, and
2 uses the end of the file as the
2835 reference point.
\var{from_what
} can be omitted and defaults to
0,
2836 using the beginning of the file as the reference point.
2839 >>> f=open('/tmp/workfile', 'r+')
2840 >>> f.write('
0123456789abcdef')
2841 >>> f.seek(
5) # Go to the
5th byte in the file
2844 >>> f.seek(-
3,
2) # Go to the
3rd byte before the end
2849 When you're done with a file, call
\code{f.close()
} to close it and
2850 free up any system resources taken up by the open file. After calling
2851 \code{f.close()
}, attempts to use the file object will automatically fail.
2856 Traceback (most recent call last):
2857 File "<stdin>", line
1, in ?
2858 ValueError: I/O operation on closed file
2861 File objects have some additional methods, such as
2862 \method{isatty()
} and
\method{truncate()
} which are less frequently
2863 used; consult the Library Reference for a complete guide to file
2866 \subsection{The
\module{pickle
} Module
\label{pickle
}}
2867 \refstmodindex{pickle
}
2869 Strings can easily be written to and read from a file. Numbers take a
2870 bit more effort, since the
\method{read()
} method only returns
2871 strings, which will have to be passed to a function like
2872 \function{string.atoi()
}, which takes a string like
\code{'
123'
} and
2873 returns its numeric value
123. However, when you want to save more
2874 complex data types like lists, dictionaries, or class instances,
2875 things get a lot more complicated.
2877 Rather than have users be constantly writing and debugging code to
2878 save complicated data types, Python provides a standard module called
2879 \module{pickle
}. This is an amazing module that can take almost
2880 any Python object (even some forms of Python code!), and convert it to
2881 a string representation; this process is called
\dfn{pickling
}.
2882 Reconstructing the object from the string representation is called
2883 \dfn{unpickling
}. Between pickling and unpickling, the string
2884 representing the object may have been stored in a file or data, or
2885 sent over a network connection to some distant machine.
2887 If you have an object
\code{x
}, and a file object
\code{f
} that's been
2888 opened for writing, the simplest way to pickle the object takes only
2895 To unpickle the object again, if
\code{f
} is a file object which has
2896 been opened for reading:
2902 (There are other variants of this, used when pickling many objects or
2903 when you don't want to write the pickled data to a file; consult the
2904 complete documentation for
\module{pickle
} in the Library Reference.)
2906 \module{pickle
} is the standard way to make Python objects which can
2907 be stored and reused by other programs or by a future invocation of
2908 the same program; the technical term for this is a
2909 \dfn{persistent
} object. Because
\module{pickle
} is so widely used,
2910 many authors who write Python extensions take care to ensure that new
2911 data types such as matrices can be properly pickled and unpickled.
2915 \chapter{Errors and Exceptions
\label{errors
}}
2917 Until now error messages haven't been more than mentioned, but if you
2918 have tried out the examples you have probably seen some. There are
2919 (at least) two distinguishable kinds of errors:
2920 \emph{syntax errors
} and
\emph{exceptions
}.
2922 \section{Syntax Errors
\label{syntaxErrors
}}
2924 Syntax errors, also known as parsing errors, are perhaps the most common
2925 kind of complaint you get while you are still learning Python:
2928 >>> while
1 print 'Hello world'
2929 File "<stdin>", line
1
2930 while
1 print 'Hello world'
2932 SyntaxError: invalid syntax
2935 The parser repeats the offending line and displays a little `arrow'
2936 pointing at the earliest point in the line where the error was
2937 detected. The error is caused by (or at least detected at) the token
2938 \emph{preceding
} the arrow: in the example, the error is detected at
2939 the keyword
\keyword{print
}, since a colon (
\character{:
}) is missing
2940 before it. File name and line number are printed so you know where to
2941 look in case the input came from a script.
2943 \section{Exceptions
\label{exceptions
}}
2945 Even if a statement or expression is syntactically correct, it may
2946 cause an error when an attempt is made to execute it.
2947 Errors detected during execution are called
\emph{exceptions
} and are
2948 not unconditionally fatal: you will soon learn how to handle them in
2949 Python programs. Most exceptions are not handled by programs,
2950 however, and result in error messages as shown here:
2954 Traceback (most recent call last):
2955 File "<stdin>", line
1
2956 ZeroDivisionError: integer division or modulo
2958 Traceback (most recent call last):
2959 File "<stdin>", line
1
2962 Traceback (most recent call last):
2963 File "<stdin>", line
1
2964 TypeError: illegal argument type for built-in operation
2967 The last line of the error message indicates what happened.
2968 Exceptions come in different types, and the type is printed as part of
2969 the message: the types in the example are
2970 \exception{ZeroDivisionError
},
\exception{NameError
} and
2971 \exception{TypeError
}.
2972 The string printed as the exception type is the name of the built-in
2973 name for the exception that occurred. This is true for all built-in
2974 exceptions, but need not be true for user-defined exceptions (although
2975 it is a useful convention).
2976 Standard exception names are built-in identifiers (not reserved
2979 The rest of the line is a detail whose interpretation depends on the
2980 exception type; its meaning is dependent on the exception type.
2982 The preceding part of the error message shows the context where the
2983 exception happened, in the form of a stack backtrace.
2984 In general it contains a stack backtrace listing source lines; however,
2985 it will not display lines read from standard input.
2987 The
\citetitle[../lib/module-exceptions.html
]{Python Library
2988 Reference
} lists the built-in exceptions and their meanings.
2991 \section{Handling Exceptions
\label{handling
}}
2993 It is possible to write programs that handle selected exceptions.
2994 Look at the following example, which asks the user for input until a
2995 valid integer has been entered, but allows the user to interrupt the
2996 program (using
\kbd{Control-C
} or whatever the operating system
2997 supports); note that a user-generated interruption is signalled by
2998 raising the
\exception{KeyboardInterrupt
} exception.
3003 ... x = int(raw_input("Please enter a number: "))
3005 ... except ValueError:
3006 ... print "Oops! That was no valid number. Try again..."
3010 The
\keyword{try
} statement works as follows.
3014 First, the
\emph{try clause
} (the statement(s) between the
3015 \keyword{try
} and
\keyword{except
} keywords) is executed.
3018 If no exception occurs, the
\emph{except\ clause
} is skipped and
3019 execution of the
\keyword{try
} statement is finished.
3022 If an exception occurs during execution of the try clause, the rest of
3023 the clause is skipped. Then if its type matches the exception named
3024 after the
\keyword{except
} keyword, the rest of the try clause is
3025 skipped, the except clause is executed, and then execution continues
3026 after the
\keyword{try
} statement.
3029 If an exception occurs which does not match the exception named in the
3030 except clause, it is passed on to outer
\keyword{try
} statements; if
3031 no handler is found, it is an
\emph{unhandled exception
} and execution
3032 stops with a message as shown above.
3036 A
\keyword{try
} statement may have more than one except clause, to
3037 specify handlers for different exceptions. At most one handler will
3038 be executed. Handlers only handle exceptions that occur in the
3039 corresponding try clause, not in other handlers of the same
3040 \keyword{try
} statement. An except clause may name multiple exceptions
3041 as a parenthesized list, e.g.:
3044 ... except (RuntimeError, TypeError, NameError):
3048 The last except clause may omit the exception name(s), to serve as a
3049 wildcard. Use this with extreme caution, since it is easy to mask a
3050 real programming error in this way! It can also be used to print an
3051 error message and then re-raise the exception (allowing a caller to
3052 handle the exception as well):
3058 f = open('myfile.txt')
3060 i = int(string.strip(s))
3061 except IOError, (errno, strerror):
3062 print "I/O error(
%s): %s" % (errno, strerror)
3064 print "Could not convert data to an integer."
3066 print "Unexpected error:", sys.exc_info()
[0]
3070 The
\keyword{try
} \ldots\
\keyword{except
} statement has an optional
3071 \emph{else clause
}, which, when present, must follow all except
3072 clauses. It is useful for code that must be executed if the try
3073 clause does not raise an exception. For example:
3076 for arg in sys.argv
[1:
]:
3080 print 'cannot open', arg
3082 print arg, 'has', len(f.readlines()), 'lines'
3086 The use of the
\keyword{else
} clause is better than adding additional
3087 code to the
\keyword{try
} clause because it avoids accidentally
3088 catching an exception that wasn't raised by the code being protected
3089 by the
\keyword{try
} \ldots\
\keyword{except
} statement.
3092 When an exception occurs, it may have an associated value, also known as
3093 the exception's
\emph{argument
}.
3094 The presence and type of the argument depend on the exception type.
3095 For exception types which have an argument, the except clause may
3096 specify a variable after the exception name (or list) to receive the
3097 argument's value, as follows:
3102 ... except NameError, x:
3103 ... print 'name', x, 'undefined'
3108 If an exception has an argument, it is printed as the last part
3109 (`detail') of the message for unhandled exceptions.
3111 Exception handlers don't just handle exceptions if they occur
3112 immediately in the try clause, but also if they occur inside functions
3113 that are called (even indirectly) in the try clause.
3117 >>> def this_fails():
3122 ... except ZeroDivisionError, detail:
3123 ... print 'Handling run-time error:', detail
3125 Handling run-time error: integer division or modulo
3129 \section{Raising Exceptions
\label{raising
}}
3131 The
\keyword{raise
} statement allows the programmer to force a
3132 specified exception to occur.
3136 >>> raise NameError, 'HiThere'
3137 Traceback (most recent call last):
3138 File "<stdin>", line
1
3142 The first argument to
\keyword{raise
} names the exception to be
3143 raised. The optional second argument specifies the exception's
3147 \section{User-defined Exceptions
\label{userExceptions
}}
3149 Programs may name their own exceptions by assigning a string to a
3150 variable or creating a new exception class. For example:
3154 ... def __init__(self, value):
3155 ... self.value = value
3156 ... def __str__(self):
3157 ... return `self.value`
3160 ... raise MyError(
2*
2)
3161 ... except MyError, e:
3162 ... print 'My exception occurred, value:', e.value
3164 My exception occurred, value:
4
3165 >>> raise MyError,
1
3166 Traceback (most recent call last):
3167 File "<stdin>", line
1
3171 Many standard modules use this to
report errors that may occur in
3172 functions they define.
3174 More information on classes is presented in chapter
\ref{classes
},
3178 \section{Defining Clean-up Actions
\label{cleanup
}}
3180 The
\keyword{try
} statement has another optional clause which is
3181 intended to define clean-up actions that must be executed under all
3182 circumstances. For example:
3186 ... raise KeyboardInterrupt
3188 ... print 'Goodbye, world!'
3191 Traceback (most recent call last):
3192 File "<stdin>", line
2
3196 A
\emph{finally clause
} is executed whether or not an exception has
3197 occurred in the try clause. When an exception has occurred, it is
3198 re-raised after the finally clause is executed. The finally clause is
3199 also executed ``on the way out'' when the
\keyword{try
} statement is
3200 left via a
\keyword{break
} or
\keyword{return
} statement.
3202 A
\keyword{try
} statement must either have one or more except clauses
3203 or one finally clause, but not both.
3205 \chapter{Classes
\label{classes
}}
3207 Python's class mechanism adds classes to the language with a minimum
3208 of new syntax and semantics. It is a mixture of the class mechanisms
3209 found in
\Cpp{} and Modula-
3. As is true for modules, classes in Python
3210 do not put an absolute barrier between definition and user, but rather
3211 rely on the politeness of the user not to ``break into the
3212 definition.'' The most important features of classes are retained
3213 with full power, however: the class inheritance mechanism allows
3214 multiple base classes, a derived class can override any methods of its
3215 base class or classes, a method can call the method of a base class with the
3216 same name. Objects can contain an arbitrary amount of private data.
3218 In
\Cpp{} terminology, all class members (including the data members) are
3219 \emph{public
}, and all member functions are
\emph{virtual
}. There are
3220 no special constructors or destructors. As in Modula-
3, there are no
3221 shorthands for referencing the object's members from its methods: the
3222 method function is declared with an explicit first argument
3223 representing the object, which is provided implicitly by the call. As
3224 in Smalltalk, classes themselves are objects, albeit in the wider
3225 sense of the word: in Python, all data types are objects. This
3226 provides semantics for importing and renaming. But, just like in
3227 \Cpp{} or Modula-
3, built-in types cannot be used as base classes for
3228 extension by the user. Also, like in
\Cpp{} but unlike in Modula-
3, most
3229 built-in operators with special syntax (arithmetic operators,
3230 subscripting etc.) can be redefined for class instances.
3232 \section{A Word About Terminology
\label{terminology
}}
3234 Lacking universally accepted terminology to talk about classes, I will
3235 make occasional use of Smalltalk and
\Cpp{} terms. (I would use Modula-
3
3236 terms, since its object-oriented semantics are closer to those of
3237 Python than
\Cpp{}, but I expect that few readers have heard of it.)
3239 I also have to warn you that there's a terminological pitfall for
3240 object-oriented readers: the word ``object'' in Python does not
3241 necessarily mean a class instance. Like
\Cpp{} and Modula-
3, and
3242 unlike Smalltalk, not all types in Python are classes: the basic
3243 built-in types like integers and lists are not, and even somewhat more
3244 exotic types like files aren't. However,
\emph{all
} Python types
3245 share a little bit of common semantics that is best described by using
3248 Objects have individuality, and multiple names (in multiple scopes)
3249 can be bound to the same object. This is known as aliasing in other
3250 languages. This is usually not appreciated on a first glance at
3251 Python, and can be safely ignored when dealing with immutable basic
3252 types (numbers, strings, tuples). However, aliasing has an
3253 (intended!) effect on the semantics of Python code involving mutable
3254 objects such as lists, dictionaries, and most types representing
3255 entities outside the program (files, windows, etc.). This is usually
3256 used to the benefit of the program, since aliases behave like pointers
3257 in some respects. For example, passing an object is cheap since only
3258 a pointer is passed by the implementation; and if a function modifies
3259 an object passed as an argument, the caller will see the change --- this
3260 obviates the need for two different argument passing mechanisms as in
3264 \section{Python Scopes and Name Spaces
\label{scopes
}}
3266 Before introducing classes, I first have to tell you something about
3267 Python's scope rules. Class definitions play some neat tricks with
3268 namespaces, and you need to know how scopes and namespaces work to
3269 fully understand what's going on. Incidentally, knowledge about this
3270 subject is useful for any advanced Python programmer.
3272 Let's begin with some definitions.
3274 A
\emph{namespace
} is a mapping from names to objects. Most
3275 namespaces are currently implemented as Python dictionaries, but
3276 that's normally not noticeable in any way (except for performance),
3277 and it may change in the future. Examples of namespaces are: the set
3278 of built-in names (functions such as
\function{abs()
}, and built-in
3279 exception names); the global names in a module; and the local names in
3280 a function invocation. In a sense the set of attributes of an object
3281 also form a namespace. The important thing to know about namespaces
3282 is that there is absolutely no relation between names in different
3283 namespaces; for instance, two different modules may both define a
3284 function ``maximize'' without confusion --- users of the modules must
3285 prefix it with the module name.
3287 By the way, I use the word
\emph{attribute
} for any name following a
3288 dot --- for example, in the expression
\code{z.real
},
\code{real
} is
3289 an attribute of the object
\code{z
}. Strictly speaking, references to
3290 names in modules are attribute references: in the expression
3291 \code{modname.funcname
},
\code{modname
} is a module object and
3292 \code{funcname
} is an attribute of it. In this case there happens to
3293 be a straightforward mapping between the module's attributes and the
3294 global names defined in the module: they share the same namespace!
3296 Except for one thing. Module objects have a secret read-only
3297 attribute called
\member{__dict__
} which returns the dictionary
3298 used to implement the module's namespace; the name
3299 \member{__dict__
} is an attribute but not a global name.
3300 Obviously, using this violates the abstraction of namespace
3301 implementation, and should be restricted to things like
3302 post-mortem debuggers.
3305 Attributes may be read-only or writable. In the latter case,
3306 assignment to attributes is possible. Module attributes are writable:
3307 you can write
\samp{modname.the_answer =
42}. Writable attributes may
3308 also be deleted with the
\keyword{del
} statement, e.g.
3309 \samp{del modname.the_answer
}.
3311 Name spaces are created at different moments and have different
3312 lifetimes. The namespace containing the built-in names is created
3313 when the Python interpreter starts up, and is never deleted. The
3314 global namespace for a module is created when the module definition
3315 is read in; normally, module namespaces also last until the
3316 interpreter quits. The statements executed by the top-level
3317 invocation of the interpreter, either read from a script file or
3318 interactively, are considered part of a module called
3319 \module{__main__
}, so they have their own global namespace. (The
3320 built-in names actually also live in a module; this is called
3321 \module{__builtin__
}.)
3323 The local namespace for a function is created when the function is
3324 called, and deleted when the function returns or raises an exception
3325 that is not handled within the function. (Actually, forgetting would
3326 be a better way to describe what actually happens.) Of course,
3327 recursive invocations each have their own local namespace.
3329 A
\emph{scope
} is a textual region of a Python program where a
3330 namespace is directly accessible. ``Directly accessible'' here means
3331 that an unqualified reference to a name attempts to find the name in
3334 Although scopes are determined statically, they are used dynamically.
3335 At any time during execution, exactly three nested scopes are in use
3336 (i.e., exactly three namespaces are directly accessible): the
3337 innermost scope, which is searched first, contains the local names,
3338 the middle scope, searched next, contains the current module's global
3339 names, and the outermost scope (searched last) is the namespace
3340 containing built-in names.
3342 Usually, the local scope references the local names of the (textually)
3343 current function. Outside of functions, the local scope references
3344 the same namespace as the global scope: the module's namespace.
3345 Class definitions place yet another namespace in the local scope.
3347 It is important to realize that scopes are determined textually: the
3348 global scope of a function defined in a module is that module's
3349 namespace, no matter from where or by what alias the function is
3350 called. On the other hand, the actual search for names is done
3351 dynamically, at run time --- however, the language definition is
3352 evolving towards static name resolution, at ``compile'' time, so don't
3353 rely on dynamic name resolution! (In fact, local variables are
3354 already determined statically.)
3356 A special quirk of Python is that assignments always go into the
3357 innermost scope. Assignments do not copy data --- they just
3358 bind names to objects. The same is true for deletions: the statement
3359 \samp{del x
} removes the binding of
\code{x
} from the namespace
3360 referenced by the local scope. In fact, all operations that introduce
3361 new names use the local scope: in particular, import statements and
3362 function definitions bind the module or function name in the local
3363 scope. (The
\keyword{global
} statement can be used to indicate that
3364 particular variables live in the global scope.)
3367 \section{A First Look at Classes
\label{firstClasses
}}
3369 Classes introduce a little bit of new syntax, three new object types,
3370 and some new semantics.
3373 \subsection{Class Definition Syntax
\label{classDefinition
}}
3375 The simplest form of class definition looks like this:
3386 Class definitions, like function definitions
3387 (
\keyword{def
} statements) must be executed before they have any
3388 effect. (You could conceivably place a class definition in a branch
3389 of an
\keyword{if
} statement, or inside a function.)
3391 In practice, the statements inside a class definition will usually be
3392 function definitions, but other statements are allowed, and sometimes
3393 useful --- we'll come back to this later. The function definitions
3394 inside a class normally have a peculiar form of argument list,
3395 dictated by the calling conventions for methods --- again, this is
3398 When a class definition is entered, a new namespace is created, and
3399 used as the local scope --- thus, all assignments to local variables
3400 go into this new namespace. In particular, function definitions bind
3401 the name of the new function here.
3403 When a class definition is left normally (via the end), a
\emph{class
3404 object
} is created. This is basically a wrapper around the contents
3405 of the namespace created by the class definition; we'll learn more
3406 about class objects in the next section. The original local scope
3407 (the one in effect just before the class definitions was entered) is
3408 reinstated, and the class object is bound here to the class name given
3409 in the class definition header (
\class{ClassName
} in the example).
3412 \subsection{Class Objects
\label{classObjects
}}
3414 Class objects support two kinds of operations: attribute references
3417 \emph{Attribute references
} use the standard syntax used for all
3418 attribute references in Python:
\code{obj.name
}. Valid attribute
3419 names are all the names that were in the class's namespace when the
3420 class object was created. So, if the class definition looked like
3425 "A simple example class"
3428 return 'hello world'
3431 then
\code{MyClass.i
} and
\code{MyClass.f
} are valid attribute
3432 references, returning an integer and a method object, respectively.
3433 Class attributes can also be assigned to, so you can change the value
3434 of
\code{MyClass.i
} by assignment.
\member{__doc__
} is also a valid
3435 attribute, returning the docstring belonging to the class:
\code{"A
3436 simple example class"
}).
3438 Class
\emph{instantiation
} uses function notation. Just pretend that
3439 the class object is a parameterless function that returns a new
3440 instance of the class. For example (assuming the above class):
3446 creates a new
\emph{instance
} of the class and assigns this object to
3447 the local variable
\code{x
}.
3449 The instantiation operation (``calling'' a class object) creates an
3450 empty object. Many classes like to create objects in a known initial
3451 state. Therefore a class may define a special method named
3452 \method{__init__()
}, like this:
3459 When a class defines an
\method{__init__()
} method, class
3460 instantiation automatically invokes
\method{__init__()
} for the
3461 newly-created class instance. So in this example, a new, initialized
3462 instance can be obtained by:
3468 Of course, the
\method{__init__()
} method may have arguments for
3469 greater flexibility. In that case, arguments given to the class
3470 instantiation operator are passed on to
\method{__init__()
}. For
3475 ... def __init__(self, realpart, imagpart):
3476 ... self.r = realpart
3477 ... self.i = imagpart
3479 >>> x = Complex(
3.0,-
4.5)
3485 \subsection{Instance Objects
\label{instanceObjects
}}
3487 Now what can we do with instance objects? The only operations
3488 understood by instance objects are attribute references. There are
3489 two kinds of valid attribute names.
3491 The first I'll call
\emph{data attributes
}. These correspond to
3492 ``instance variables'' in Smalltalk, and to ``data members'' in
3493 \Cpp{}. Data attributes need not be declared; like local variables,
3494 they spring into existence when they are first assigned to. For
3495 example, if
\code{x
} is the instance of
\class{MyClass
} created above,
3496 the following piece of code will print the value
\code{16}, without
3501 while x.counter <
10:
3502 x.counter = x.counter *
2
3507 The second kind of attribute references understood by instance objects
3508 are
\emph{methods
}. A method is a function that ``belongs to'' an
3509 object. (In Python, the term method is not unique to class instances:
3510 other object types can have methods as well, e.g., list objects have
3511 methods called append, insert, remove, sort, and so on. However,
3512 below, we'll use the term method exclusively to mean methods of class
3513 instance objects, unless explicitly stated otherwise.)
3515 Valid method names of an instance object depend on its class. By
3516 definition, all attributes of a class that are (user-defined) function
3517 objects define corresponding methods of its instances. So in our
3518 example,
\code{x.f
} is a valid method reference, since
3519 \code{MyClass.f
} is a function, but
\code{x.i
} is not, since
3520 \code{MyClass.i
} is not. But
\code{x.f
} is not the same thing as
3521 \code{MyClass.f
} --- it is a
\obindex{method
}\emph{method object
}, not
3525 \subsection{Method Objects
\label{methodObjects
}}
3527 Usually, a method is called immediately, e.g.:
3533 In our example, this will return the string
\code{'hello world'
}.
3534 However, it is not necessary to call a method right away:
3535 \code{x.f
} is a method object, and can be stored away and called at a
3536 later time. For example:
3544 will continue to print
\samp{hello world
} until the end of time.
3546 What exactly happens when a method is called? You may have noticed
3547 that
\code{x.f()
} was called without an argument above, even though
3548 the function definition for
\method{f
} specified an argument. What
3549 happened to the argument? Surely Python raises an exception when a
3550 function that requires an argument is called without any --- even if
3551 the argument isn't actually used...
3553 Actually, you may have guessed the answer: the special thing about
3554 methods is that the object is passed as the first argument of the
3555 function. In our example, the call
\code{x.f()
} is exactly equivalent
3556 to
\code{MyClass.f(x)
}. In general, calling a method with a list of
3557 \var{n
} arguments is equivalent to calling the corresponding function
3558 with an argument list that is created by inserting the method's object
3559 before the first argument.
3561 If you still don't understand how methods work, a look at the
3562 implementation can perhaps clarify matters. When an instance
3563 attribute is referenced that isn't a data attribute, its class is
3564 searched. If the name denotes a valid class attribute that is a
3565 function object, a method object is created by packing (pointers to)
3566 the instance object and the function object just found together in an
3567 abstract object: this is the method object. When the method object is
3568 called with an argument list, it is unpacked again, a new argument
3569 list is constructed from the instance object and the original argument
3570 list, and the function object is called with this new argument list.
3573 \section{Random Remarks
\label{remarks
}}
3575 [These should perhaps be placed more carefully...
]
3578 Data attributes override method attributes with the same name; to
3579 avoid accidental name conflicts, which may cause hard-to-find bugs in
3580 large programs, it is wise to use some kind of convention that
3581 minimizes the chance of conflicts, e.g., capitalize method names,
3582 prefix data attribute names with a small unique string (perhaps just
3583 an underscore), or use verbs for methods and nouns for data attributes.
3586 Data attributes may be referenced by methods as well as by ordinary
3587 users (``clients'') of an object. In other words, classes are not
3588 usable to implement pure abstract data types. In fact, nothing in
3589 Python makes it possible to enforce data hiding --- it is all based
3590 upon convention. (On the other hand, the Python implementation,
3591 written in C, can completely hide implementation details and control
3592 access to an object if necessary; this can be used by extensions to
3593 Python written in C.)
3596 Clients should use data attributes with care --- clients may mess up
3597 invariants maintained by the methods by stamping on their data
3598 attributes. Note that clients may add data attributes of their own to
3599 an instance object without affecting the validity of the methods, as
3600 long as name conflicts are avoided --- again, a naming convention can
3601 save a lot of headaches here.
3604 There is no shorthand for referencing data attributes (or other
3605 methods!) from within methods. I find that this actually increases
3606 the readability of methods: there is no chance of confusing local
3607 variables and instance variables when glancing through a method.
3610 Conventionally, the first argument of methods is often called
3611 \code{self
}. This is nothing more than a convention: the name
3612 \code{self
} has absolutely no special meaning to Python. (Note,
3613 however, that by not following the convention your code may be less
3614 readable by other Python programmers, and it is also conceivable that
3615 a
\emph{class browser
} program be written which relies upon such a
3619 Any function object that is a class attribute defines a method for
3620 instances of that class. It is not necessary that the function
3621 definition is textually enclosed in the class definition: assigning a
3622 function object to a local variable in the class is also ok. For
3626 # Function defined outside the class
3633 return 'hello world'
3637 Now
\code{f
},
\code{g
} and
\code{h
} are all attributes of class
3638 \class{C
} that refer to function objects, and consequently they are all
3639 methods of instances of
\class{C
} ---
\code{h
} being exactly equivalent
3640 to
\code{g
}. Note that this practice usually only serves to confuse
3641 the reader of a program.
3644 Methods may call other methods by using method attributes of the
3645 \code{self
} argument, e.g.:
3653 def addtwice(self, x):
3658 Methods may reference global names in the same way as ordinary
3659 functions. The global scope associated with a method is the module
3660 containing the class definition. (The class itself is never used as a
3661 global scope!) While one rarely encounters a good reason for using
3662 global data in a method, there are many legitimate uses of the global
3663 scope: for one thing, functions and modules imported into the global
3664 scope can be used by methods, as well as functions and classes defined
3665 in it. Usually, the class containing the method is itself defined in
3666 this global scope, and in the next section we'll find some good
3667 reasons why a method would want to reference its own class!
3670 \section{Inheritance
\label{inheritance
}}
3672 Of course, a language feature would not be worthy of the name ``class''
3673 without supporting inheritance. The syntax for a derived class
3674 definition looks as follows:
3677 class DerivedClassName(BaseClassName):
3685 The name
\class{BaseClassName
} must be defined in a scope containing
3686 the derived class definition. Instead of a base class name, an
3687 expression is also allowed. This is useful when the base class is
3688 defined in another module, e.g.,
3691 class DerivedClassName(modname.BaseClassName):
3694 Execution of a derived class definition proceeds the same as for a
3695 base class. When the class object is constructed, the base class is
3696 remembered. This is used for resolving attribute references: if a
3697 requested attribute is not found in the class, it is searched in the
3698 base class. This rule is applied recursively if the base class itself
3699 is derived from some other class.
3701 There's nothing special about instantiation of derived classes:
3702 \code{DerivedClassName()
} creates a new instance of the class. Method
3703 references are resolved as follows: the corresponding class attribute
3704 is searched, descending down the chain of base classes if necessary,
3705 and the method reference is valid if this yields a function object.
3707 Derived classes may override methods of their base classes. Because
3708 methods have no special privileges when calling other methods of the
3709 same object, a method of a base class that calls another method
3710 defined in the same base class, may in fact end up calling a method of
3711 a derived class that overrides it. (For
\Cpp{} programmers: all methods
3712 in Python are effectively
\keyword{virtual
}.)
3714 An overriding method in a derived class may in fact want to extend
3715 rather than simply replace the base class method of the same name.
3716 There is a simple way to call the base class method directly: just
3717 call
\samp{BaseClassName.methodname(self, arguments)
}. This is
3718 occasionally useful to clients as well. (Note that this only works if
3719 the base class is defined or imported directly in the global scope.)
3722 \subsection{Multiple Inheritance
\label{multiple
}}
3724 Python supports a limited form of multiple inheritance as well. A
3725 class definition with multiple base classes looks as follows:
3728 class DerivedClassName(Base1, Base2, Base3):
3736 The only rule necessary to explain the semantics is the resolution
3737 rule used for class attribute references. This is depth-first,
3738 left-to-right. Thus, if an attribute is not found in
3739 \class{DerivedClassName
}, it is searched in
\class{Base1
}, then
3740 (recursively) in the base classes of
\class{Base1
}, and only if it is
3741 not found there, it is searched in
\class{Base2
}, and so on.
3743 (To some people breadth first --- searching
\class{Base2
} and
3744 \class{Base3
} before the base classes of
\class{Base1
} --- looks more
3745 natural. However, this would require you to know whether a particular
3746 attribute of
\class{Base1
} is actually defined in
\class{Base1
} or in
3747 one of its base classes before you can figure out the consequences of
3748 a name conflict with an attribute of
\class{Base2
}. The depth-first
3749 rule makes no differences between direct and inherited attributes of
3752 It is clear that indiscriminate use of multiple inheritance is a
3753 maintenance nightmare, given the reliance in Python on conventions to
3754 avoid accidental name conflicts. A well-known problem with multiple
3755 inheritance is a class derived from two classes that happen to have a
3756 common base class. While it is easy enough to figure out what happens
3757 in this case (the instance will have a single copy of ``instance
3758 variables'' or data attributes used by the common base class), it is
3759 not clear that these semantics are in any way useful.
3762 \section{Private Variables
\label{private
}}
3764 There is limited support for class-private
3765 identifiers. Any identifier of the form
\code{__spam
} (at least two
3766 leading underscores, at most one trailing underscore) is now textually
3767 replaced with
\code{_classname__spam
}, where
\code{classname
} is the
3768 current class name with leading underscore(s) stripped. This mangling
3769 is done without regard of the syntactic position of the identifier, so
3770 it can be used to define class-private instance and class variables,
3771 methods, as well as globals, and even to store instance variables
3772 private to this class on instances of
\emph{other
} classes. Truncation
3773 may occur when the mangled name would be longer than
255 characters.
3774 Outside classes, or when the class name consists of only underscores,
3777 Name mangling is intended to give classes an easy way to define
3778 ``private'' instance variables and methods, without having to worry
3779 about instance variables defined by derived classes, or mucking with
3780 instance variables by code outside the class. Note that the mangling
3781 rules are designed mostly to avoid accidents; it still is possible for
3782 a determined soul to access or modify a variable that is considered
3783 private. This can even be useful, e.g. for the debugger, and that's
3784 one reason why this loophole is not closed. (Buglet: derivation of a
3785 class with the same name as the base class makes use of private
3786 variables of the base class possible.)
3788 Notice that code passed to
\code{exec
},
\code{eval()
} or
3789 \code{evalfile()
} does not consider the classname of the invoking
3790 class to be the current class; this is similar to the effect of the
3791 \code{global
} statement, the effect of which is likewise restricted to
3792 code that is byte-compiled together. The same restriction applies to
3793 \code{getattr()
},
\code{setattr()
} and
\code{delattr()
}, as well as
3794 when referencing
\code{__dict__
} directly.
3796 Here's an example of a class that implements its own
3797 \method{__getattr__()
} and
\method{__setattr__()
} methods and stores
3798 all attributes in a private variable, in a way that works in all
3799 versions of Python, including those available before this feature was
3803 class VirtualAttributes:
3805 __vdict_name = locals().keys()
[0]
3808 self.__dict__
[self.__vdict_name
] =
{}
3810 def __getattr__(self, name):
3811 return self.__vdict
[name
]
3813 def __setattr__(self, name, value):
3814 self.__vdict
[name
] = value
3818 \section{Odds and Ends
\label{odds
}}
3820 Sometimes it is useful to have a data type similar to the Pascal
3821 ``record'' or C ``struct'', bundling together a couple of named data
3822 items. An empty class definition will do nicely, e.g.:
3828 john = Employee() # Create an empty employee record
3830 # Fill the fields of the record
3831 john.name = 'John Doe'
3832 john.dept = 'computer lab'
3836 A piece of Python code that expects a particular abstract data type
3837 can often be passed a class that emulates the methods of that data
3838 type instead. For instance, if you have a function that formats some
3839 data from a file object, you can define a class with methods
3840 \method{read()
} and
\method{readline()
} that gets the data from a string
3841 buffer instead, and pass it as an argument.
% (Unfortunately, this
3842 %technique has its limitations: a class can't define operations that
3843 %are accessed by special syntax such as sequence subscripting or
3844 %arithmetic operators, and assigning such a ``pseudo-file'' to
3845 %\code{sys.stdin} will not cause the interpreter to read further input
3849 Instance method objects have attributes, too:
\code{m.im_self
} is the
3850 object of which the method is an instance, and
\code{m.im_func
} is the
3851 function object corresponding to the method.
3853 \subsection{Exceptions Can Be Classes
\label{exceptionClasses
}}
3855 User-defined exceptions are no longer limited to being string objects
3856 --- they can be identified by classes as well. Using this mechanism it
3857 is possible to create extensible hierarchies of exceptions.
3859 There are two new valid (semantic) forms for the raise statement:
3862 raise Class, instance
3867 In the first form,
\code{instance
} must be an instance of
3868 \class{Class
} or of a class derived from it. The second form is a
3872 raise instance.__class__, instance
3875 An except clause may list classes as well as string objects. A class
3876 in an except clause is compatible with an exception if it is the same
3877 class or a base class thereof (but not the other way around --- an
3878 except clause listing a derived class is not compatible with a base
3879 class). For example, the following code will print B, C, D in that
3901 Note that if the except clauses were reversed (with
3902 \samp{except B
} first), it would have printed B, B, B --- the first
3903 matching except clause is triggered.
3905 When an error message is printed for an unhandled exception which is a
3906 class, the class name is printed, then a colon and a space, and
3907 finally the instance converted to a string using the built-in function
3911 \chapter{What Now?
\label{whatNow
}}
3913 Hopefully reading this tutorial has reinforced your interest in using
3914 Python. Now what should you do?
3916 You should read, or at least page through, the Library Reference,
3917 which gives complete (though terse) reference material about types,
3918 functions, and modules that can save you a lot of time when writing
3919 Python programs. The standard Python distribution includes a
3920 \emph{lot
} of code in both C and Python; there are modules to read
3921 \UNIX{} mailboxes, retrieve documents via HTTP, generate random
3922 numbers, parse command-line options, write CGI programs, compress
3923 data, and a lot more; skimming through the Library Reference will give
3924 you an idea of what's available.
3926 The major Python Web site is
\url{http://www.python.org/
}; it contains
3927 code, documentation, and pointers to Python-related pages around the
3928 Web. This web site is mirrored in various places around the
3929 world, such as Europe, Japan, and Australia; a mirror may be faster
3930 than the main site, depending on your geographical location. A more
3931 informal site is
\url{http://starship.python.net/
}, which contains a
3932 bunch of Python-related personal home pages; many people have
3933 downloadable software there.
3935 For Python-related questions and problem reports, you can post to the
3936 newsgroup
\newsgroup{comp.lang.python
}, or send them to the mailing
3937 list at
\email{python-list@python.org
}. The newsgroup and mailing list
3938 are gatewayed, so messages posted to one will automatically be
3939 forwarded to the other. There are around
120 postings a day,
3940 % Postings figure based on average of last six months activity as
3941 % reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182
3942 % days = 116.9 msgs / day and steadily increasing.
3943 asking (and answering) questions, suggesting new features, and
3944 announcing new modules. Before posting, be sure to check the list of
3945 Frequently Asked Questions (also called the FAQ), at
3946 \url{http://www.python.org/doc/FAQ.html
}, or look for it in the
3947 \file{Misc/
} directory of the Python source distribution. Mailing
3948 list archives are available at
\url{http://www.python.org/pipermail/
}.
3949 The FAQ answers many of the questions that come up again and again,
3950 and may already contain the solution for your problem.
3955 \chapter{Interactive Input Editing and History Substitution
3956 \label{interacting
}}
3958 Some versions of the Python interpreter support editing of the current
3959 input line and history substitution, similar to facilities found in
3960 the Korn shell and the GNU Bash shell. This is implemented using the
3961 \emph{GNU Readline
} library, which supports Emacs-style and vi-style
3962 editing. This library has its own documentation which I won't
3963 duplicate here; however, the basics are easily explained. The
3964 interactive editing and history described here are optionally
3965 available in the
\UNIX{} and CygWin versions of the interpreter.
3967 This chapter does
\emph{not
} document the editing facilities of Mark
3968 Hammond's PythonWin package or the Tk-based environment, IDLE,
3969 distributed with Python. The command line history recall which
3970 operates within DOS boxes on NT and some other DOS and Windows flavors
3971 is yet another beast.
3973 \section{Line Editing
\label{lineEditing
}}
3975 If supported, input line editing is active whenever the interpreter
3976 prints a primary or secondary prompt. The current line can be edited
3977 using the conventional Emacs control characters. The most important
3978 of these are:
\kbd{C-A
} (Control-A) moves the cursor to the beginning
3979 of the line,
\kbd{C-E
} to the end,
\kbd{C-B
} moves it one position to
3980 the left,
\kbd{C-F
} to the right. Backspace erases the character to
3981 the left of the cursor,
\kbd{C-D
} the character to its right.
3982 \kbd{C-K
} kills (erases) the rest of the line to the right of the
3983 cursor,
\kbd{C-Y
} yanks back the last killed string.
3984 \kbd{C-underscore
} undoes the last change you made; it can be repeated
3985 for cumulative effect.
3987 \section{History Substitution
\label{history
}}
3989 History substitution works as follows. All non-empty input lines
3990 issued are saved in a history buffer, and when a new prompt is given
3991 you are positioned on a new line at the bottom of this buffer.
3992 \kbd{C-P
} moves one line up (back) in the history buffer,
3993 \kbd{C-N
} moves one down. Any line in the history buffer can be
3994 edited; an asterisk appears in front of the prompt to mark a line as
3995 modified. Pressing the
\kbd{Return
} key passes the current line to
3996 the interpreter.
\kbd{C-R
} starts an incremental reverse search;
3997 \kbd{C-S
} starts a forward search.
3999 \section{Key Bindings
\label{keyBindings
}}
4001 The key bindings and some other parameters of the Readline library can
4002 be customized by placing commands in an initialization file called
4003 \file{\~
{}/.inputrc
}. Key bindings have the form
4006 key-name: function-name
4012 "string": function-name
4015 and options can be set with
4018 set option-name value
4024 # I prefer vi-style editing:
4027 # Edit using a single line:
4028 set horizontal-scroll-mode On
4031 Meta-h: backward-kill-word
4032 "
\C-u": universal-argument
4033 "
\C-x
\C-r": re-read-init-file
4036 Note that the default binding for
\kbd{Tab
} in Python is to insert a
4037 \kbd{Tab
} character instead of Readline's default filename completion
4038 function. If you insist, you can override this by putting
4044 in your
\file{\~
{}/.inputrc
}. (Of course, this makes it harder to
4045 type indented continuation lines.)
4047 Automatic completion of variable and module names is optionally
4048 available. To enable it in the interpreter's interactive mode, add
4049 the following to your startup file:
\footnote{
4050 Python will execute the contents of a file identified by the
4051 \envvar{PYTHONSTARTUP
} environment variable when you start an
4052 interactive interpreter.
}
4053 \refstmodindex{rlcompleter
}\refbimodindex{readline
}
4056 import rlcompleter, readline
4057 readline.parse_and_bind('tab: complete')
4060 This binds the TAB key to the completion function, so hitting the TAB
4061 key twice suggests completions; it looks at Python statement names,
4062 the current local variables, and the available module names. For
4063 dotted expressions such as
\code{string.a
}, it will evaluate the the
4064 expression up to the final
\character{.
} and then suggest completions
4065 from the attributes of the resulting object. Note that this may
4066 execute application-defined code if an object with a
4067 \method{__getattr__()
} method is part of the expression.
4070 \section{Commentary
\label{commentary
}}
4072 This facility is an enormous step forward compared to earlier versions
4073 of the interpreter; however, some wishes are left: It would be nice if
4074 the proper indentation were suggested on continuation lines (the
4075 parser knows if an indent token is required next). The completion
4076 mechanism might use the interpreter's symbol table. A command to
4077 check (or even suggest) matching parentheses, quotes, etc., would also