4 % Add a section on file I/O
5 % Write a chapter entitled ``Some Useful Modules''
7 % Should really move the Python startup file info to an appendix
9 \title{Python Tutorial
}
18 \chapter*
{Front Matter
\label{front
}}
26 Python is an easy to learn, powerful programming language. It has
27 efficient high-level data structures and a simple but effective
28 approach to object-oriented programming. Python's elegant syntax and
29 dynamic typing, together with its interpreted nature, make it an ideal
30 language for scripting and rapid application development in many areas
33 The Python interpreter and the extensive standard library are freely
34 available in source or binary form for all major platforms from the
35 Python web site,
\url{http://www.python.org
}, and can be freely
36 distributed. The same site also contains distributions of and
37 pointers to many free third party Python modules, programs and tools,
38 and additional documentation.
40 The Python interpreter is easily extended with new functions and data
41 types implemented in C or
\Cpp{} (or other languages callable from C).
42 Python is also suitable as an extension language for customizable
45 This tutorial introduces the reader informally to the basic concepts
46 and features of the Python language and system. It helps to have a
47 Python interpreter handy for hands-on experience, but all examples are
48 self-contained, so the tutorial can be read off-line as well.
50 For a description of standard objects and modules, see the
51 \citetitle[../lib/lib.html
]{Python Library Reference
} document. The
52 \citetitle[../ref/ref.html
]{Python Reference Manual
} gives a more
53 formal definition of the language. To write extensions in C or
54 \Cpp{}, read
\citetitle[../ext/ext.html
]{Extending and Embedding the
55 Python Interpreter
} and
\citetitle[../api/api.html
]{Python/C API
56 Reference
}. There are also several books covering Python in depth.
58 This tutorial does not attempt to be comprehensive and cover every
59 single feature, or even every commonly used feature. Instead, it
60 introduces many of Python's most noteworthy features, and will give
61 you a good idea of the language's flavor and style. After reading it,
62 you will be able to read and write Python modules and programs, and
63 you will be ready to learn more about the various Python library
64 modules described in the
\citetitle[../lib/lib.html
]{Python Library
72 \chapter{Whetting Your Appetite
\label{intro
}}
74 If you ever wrote a large shell script, you probably know this
75 feeling: you'd love to add yet another feature, but it's already so
76 slow, and so big, and so complicated; or the feature involves a system
77 call or other function that is only accessible from C
\ldots Usually
78 the problem at hand isn't serious enough to warrant rewriting the
79 script in C; perhaps the problem requires variable-length strings or
80 other data types (like sorted lists of file names) that are easy in
81 the shell but lots of work to implement in C, or perhaps you're not
82 sufficiently familiar with C.
84 Another situation: perhaps you have to work with several C libraries,
85 and the usual C write/compile/test/re-compile cycle is too slow. You
86 need to develop software more quickly. Possibly perhaps you've
87 written a program that could use an extension language, and you don't
88 want to design a language, write and debug an interpreter for it, then
89 tie it into your application.
91 In such cases, Python may be just the language for you. Python is
92 simple to use, but it is a real programming language, offering much
93 more structure and support for large programs than the shell has. On
94 the other hand, it also offers much more error checking than C, and,
95 being a
\emph{very-high-level language
}, it has high-level data types
96 built in, such as flexible arrays and dictionaries that would cost you
97 days to implement efficiently in C. Because of its more general data
98 types Python is applicable to a much larger problem domain than
99 \emph{Awk
} or even
\emph{Perl
}, yet many things are at least as easy
100 in Python as in those languages.
102 Python allows you to split up your program in modules that can be
103 reused in other Python programs. It comes with a large collection of
104 standard modules that you can use as the basis of your programs --- or
105 as examples to start learning to program in Python. There are also
106 built-in modules that provide things like file I/O, system calls,
107 sockets, and even interfaces to GUI toolkits like Tk.
109 Python is an interpreted language, which can save you considerable time
110 during program development because no compilation and linking is
111 necessary. The interpreter can be used interactively, which makes it
112 easy to experiment with features of the language, to write throw-away
113 programs, or to test functions during bottom-up program development.
114 It is also a handy desk calculator.
116 Python allows writing very compact and readable programs. Programs
117 written in Python are typically much shorter than equivalent C or
118 \Cpp{} programs, for several reasons:
121 the high-level data types allow you to express complex operations in a
124 statement grouping is done by indentation instead of begin/end
127 no variable or argument declarations are necessary.
130 Python is
\emph{extensible
}: if you know how to program in C it is easy
131 to add a new built-in function or module to the interpreter, either to
132 perform critical operations at maximum speed, or to link Python
133 programs to libraries that may only be available in binary form (such
134 as a vendor-specific graphics library). Once you are really hooked,
135 you can link the Python interpreter into an application written in C
136 and use it as an extension or command language for that application.
138 By the way, the language is named after the BBC show ``Monty Python's
139 Flying Circus'' and has nothing to do with nasty reptiles. Making
140 references to Monty Python skits in documentation is not only allowed,
143 \section{Where From Here
\label{where
}}
145 Now that you are all excited about Python, you'll want to examine it
146 in some more detail. Since the best way to learn a language is
147 using it, you are invited here to do so.
149 In the next chapter, the mechanics of using the interpreter are
150 explained. This is rather mundane information, but essential for
151 trying out the examples shown later.
153 The rest of the tutorial introduces various features of the Python
154 language and system through examples, beginning with simple
155 expressions, statements and data types, through functions and modules,
156 and finally touching upon advanced concepts like exceptions
157 and user-defined classes.
159 \chapter{Using the Python Interpreter
\label{using
}}
161 \section{Invoking the Interpreter
\label{invoking
}}
163 The Python interpreter is usually installed as
164 \file{/usr/local/bin/python
} on those machines where it is available;
165 putting
\file{/usr/local/bin
} in your
\UNIX{} shell's search path
166 makes it possible to start it by typing the command
172 to the shell. Since the choice of the directory where the interpreter
173 lives is an installation option, other places are possible; check with
174 your local Python guru or system administrator. (E.g.,
175 \file{/usr/local/python
} is a popular alternative location.)
177 Typing an
\EOF{} character (
\kbd{Control-D
} on
\UNIX,
178 \kbd{Control-Z
} on DOS or Windows) at the primary prompt causes the
179 interpreter to exit with a zero exit status. If that doesn't work,
180 you can exit the interpreter by typing the following commands:
181 \samp{import sys; sys.exit()
}.
183 The interpreter's line-editing features usually aren't very
184 sophisticated. On
\UNIX{}, whoever installed the interpreter may have
185 enabled support for the GNU readline library, which adds more
186 elaborate interactive editing and history features. Perhaps the
187 quickest check to see whether command line editing is supported is
188 typing Control-P to the first Python prompt you get. If it beeps, you
189 have command line editing; see Appendix
\ref{interacting
} for an
190 introduction to the keys. If nothing appears to happen, or if
191 \code{\^P
} is echoed, command line editing isn't available; you'll
192 only be able to use backspace to remove characters from the current
195 The interpreter operates somewhat like the
\UNIX{} shell: when called
196 with standard input connected to a tty device, it reads and executes
197 commands interactively; when called with a file name argument or with
198 a file as standard input, it reads and executes a
\emph{script
} from
201 A third way of starting the interpreter is
202 \samp{\program{python
} \programopt{-c
} \var{command
} [arg
] ...
}, which
203 executes the statement(s) in
\var{command
}, analogous to the shell's
204 \programopt{-c
} option. Since Python statements often contain spaces
205 or other characters that are special to the shell, it is best to quote
206 \var{command
} in its entirety with double quotes.
208 Note that there is a difference between
\samp{python file
} and
209 \samp{python <file
}. In the latter case, input requests from the
210 program, such as calls to
\code{input()
} and
\code{raw_input()
}, are
211 satisfied from
\emph{file
}. Since this file has already been read
212 until the end by the parser before the program starts executing, the
213 program will encounter EOF immediately. In the former case (which is
214 usually what you want) they are satisfied from whatever file or device
215 is connected to standard input of the Python interpreter.
217 When a script file is used, it is sometimes useful to be able to run
218 the script and enter interactive mode afterwards. This can be done by
219 passing
\programopt{-i
} before the script. (This does not work if the
220 script is read from standard input, for the same reason as explained
221 in the previous paragraph.)
223 \subsection{Argument Passing
\label{argPassing
}}
225 When known to the interpreter, the script name and additional
226 arguments thereafter are passed to the script in the variable
227 \code{sys.argv
}, which is a list of strings. Its length is at least
228 one; when no script and no arguments are given,
\code{sys.argv
[0]} is
229 an empty string. When the script name is given as
\code{'-'
} (meaning
230 standard input),
\code{sys.argv
[0]} is set to
\code{'-'
}. When
231 \programopt{-c
} \var{command
} is used,
\code{sys.argv
[0]} is set to
232 \code{'-c'
}. Options found after
\programopt{-c
} \var{command
} are
233 not consumed by the Python interpreter's option processing but left in
234 \code{sys.argv
} for the command to handle.
236 \subsection{Interactive Mode
\label{interactive
}}
238 When commands are read from a tty, the interpreter is said to be in
239 \emph{interactive mode
}. In this mode it prompts for the next command
240 with the
\emph{primary prompt
}, usually three greater-than signs
241 (
\samp{>
\code{>
}>~
}); for continuation lines it prompts with the
242 \emph{secondary prompt
}, by default three dots (
\samp{...~
}).
243 The interpreter prints a welcome message stating its version number
244 and a copyright notice before printing the first prompt, e.g.:
248 Python
1.5.2b2 (
#1, Feb
28 1999,
00:
02:
06)
[GCC
2.8.1] on sunos5
249 Copyright
1991-
1995 Stichting Mathematisch Centrum, Amsterdam
253 Continuation lines are needed when entering a multi-line construct.
254 As an example, take a look at this
\keyword{if
} statement:
257 >>> the_world_is_flat =
1
258 >>> if the_world_is_flat:
259 ... print "Be careful not to fall off!"
261 Be careful not to fall off!
265 \section{The Interpreter and Its Environment
\label{interp
}}
267 \subsection{Error Handling
\label{error
}}
269 When an error occurs, the interpreter prints an error
270 message and a stack trace. In interactive mode, it then returns to
271 the primary prompt; when input came from a file, it exits with a
272 nonzero exit status after printing
273 the stack trace. (Exceptions handled by an
\code{except
} clause in a
274 \code{try
} statement are not errors in this context.) Some errors are
275 unconditionally fatal and cause an exit with a nonzero exit; this
276 applies to internal inconsistencies and some cases of running out of
277 memory. All error messages are written to the standard error stream;
278 normal output from the executed commands is written to standard
281 Typing the interrupt character (usually Control-C or DEL) to the
282 primary or secondary prompt cancels the input and returns to the
283 primary prompt.
\footnote{
284 A problem with the GNU Readline package may prevent this.
286 Typing an interrupt while a command is executing raises the
287 \code{KeyboardInterrupt
} exception, which may be handled by a
288 \code{try
} statement.
290 \subsection{Executable Python Scripts
\label{scripts
}}
292 On BSD'ish
\UNIX{} systems, Python scripts can be made directly
293 executable, like shell scripts, by putting the line
296 #! /usr/bin/env python
299 (assuming that the interpreter is on the user's
\envvar{PATH
}) at the
300 beginning of the script and giving the file an executable mode. The
301 \samp{\#!
} must be the first two characters of the file. Note that
302 the hash, or pound, character,
\character{\#
}, is used to start a
305 \subsection{The Interactive Startup File
\label{startup
}}
307 % XXX This should probably be dumped in an appendix, since most people
308 % don't use Python interactively in non-trivial ways.
310 When you use Python interactively, it is frequently handy to have some
311 standard commands executed every time the interpreter is started. You
312 can do this by setting an environment variable named
313 \envvar{PYTHONSTARTUP
} to the name of a file containing your start-up
314 commands. This is similar to the
\file{.profile
} feature of the
317 This file is only read in interactive sessions, not when Python reads
318 commands from a script, and not when
\file{/dev/tty
} is given as the
319 explicit source of commands (which otherwise behaves like an
320 interactive session). It is executed in the same namespace where
321 interactive commands are executed, so that objects that it defines or
322 imports can be used without qualification in the interactive session.
323 You can also change the prompts
\code{sys.ps1
} and
\code{sys.ps2
} in
326 If you want to read an additional start-up file from the current
327 directory, you can program this in the global start-up file,
328 e.g.\
\samp{if os.path.isfile('.pythonrc.py'):
329 execfile('.pythonrc.py')
}. If you want to use the startup file in a
330 script, you must do this explicitly in the script:
334 filename = os.environ.get('PYTHONSTARTUP')
335 if filename and os.path.isfile(filename):
340 \chapter{An Informal Introduction to Python
\label{informal
}}
342 In the following examples, input and output are distinguished by the
343 presence or absence of prompts (
\samp{>
\code{>
}>~
} and
\samp{...~
}): to repeat
344 the example, you must type everything after the prompt, when the
345 prompt appears; lines that do not begin with a prompt are output from
348 % I'd prefer to use different fonts to distinguish input
349 % from output, but the amount of LaTeX hacking that would require
350 % is currently beyond my ability.
352 Note that a secondary prompt on a line by itself in an example means
353 you must type a blank line; this is used to end a multi-line command.
355 Many of the examples in this manual, even those entered at the
356 interactive prompt, include comments. Comments in Python start with
357 the hash character,
\character{\#
}, and extend to the end of the
358 physical line. A comment may appear at the start of a line or
359 following whitespace or code, but not within a string literal. A hash
360 character within a string literal is just a hash character.
365 # this is the first comment
366 SPAM =
1 # and this is the second comment
367 # ... and now a third!
368 STRING = "# This is not a comment."
372 \section{Using Python as a Calculator
\label{calculator
}}
374 Let's try some simple Python commands. Start the interpreter and wait
375 for the primary prompt,
\samp{>
\code{>
}>~
}. (It shouldn't take long.)
377 \subsection{Numbers
\label{numbers
}}
379 The interpreter acts as a simple calculator: you can type an
380 expression at it and it will write the value. Expression syntax is
381 straightforward: the operators
\code{+
},
\code{-
},
\code{*
} and
382 \code{/
} work just like in most other languages (for example, Pascal
383 or C); parentheses can be used for grouping. For example:
388 >>> # This is a comment
391 >>>
2+
2 # and a comment on the same line as code
395 >>> # Integer division returns the floor:
402 Like in C, the equal sign (
\character{=
}) is used to assign a value to a
403 variable. The value of an assignment is not written:
412 A value can be assigned to several variables simultaneously:
415 >>> x = y = z =
0 # Zero x, y and z
424 There is full support for floating point; operators with mixed type
425 operands convert the integer operand to floating point:
434 Complex numbers are also supported; imaginary numbers are written with
435 a suffix of
\samp{j
} or
\samp{J
}. Complex numbers with a nonzero
436 real component are written as
\samp{(
\var{real
}+
\var{imag
}j)
}, or can
437 be created with the
\samp{complex(
\var{real
},
\var{imag
})
} function.
442 >>>
1j * complex(
0,
1)
452 Complex numbers are always represented as two floating point numbers,
453 the real and imaginary part. To extract these parts from a complex
454 number
\var{z
}, use
\code{\var{z
}.real
} and
\code{\var{z
}.imag
}.
464 The conversion functions to floating point and integer
465 (
\function{float()
},
\function{int()
} and
\function{long()
}) don't
466 work for complex numbers --- there is no one correct way to convert a
467 complex number to a real number. Use
\code{abs(
\var{z
})
} to get its
468 magnitude (as a float) or
\code{z.real
} to get its real part.
473 Traceback (innermost last):
474 File "<stdin>", line
1, in ?
475 TypeError: can't convert complex to float; use e.g. abs(z)
482 In interactive mode, the last printed expression is assigned to the
483 variable
\code{_
}. This means that when you are using Python as a
484 desk calculator, it is somewhat easier to continue calculations, for
498 This variable should be treated as read-only by the user. Don't
499 explicitly assign a value to it --- you would create an independent
500 local variable with the same name masking the built-in variable with
503 \subsection{Strings
\label{strings
}}
505 Besides numbers, Python can also manipulate strings, which can be
506 expressed in several ways. They can be enclosed in single quotes or
516 >>> '"Yes," he said.'
518 >>> "\"Yes,\" he said."
520 >>> '"Isn\'t," she said.'
521 '"Isn\'t," she said.'
524 String literals can span multiple lines in several ways. Newlines can
525 be escaped with backslashes, e.g.:
528 hello = "This is a rather long string containing
\n\
529 several lines of text just as you would do in C.
\n\
530 Note that whitespace at the beginning of the line is\
535 which would print the following:
538 This is a rather long string containing
539 several lines of text just as you would do in C.
540 Note that whitespace at the beginning of the line is significant.
543 Or, strings can be surrounded in a pair of matching triple-quotes:
544 \code{"""
} or
\code {'''
}. End of lines do not need to be escaped
545 when using triple-quotes, but they will be included in the string.
549 Usage: thingy
[OPTIONS
]
550 -h Display this usage message
551 -H hostname Hostname to connect to
555 produces the following output:
558 Usage: thingy
[OPTIONS
]
559 -h Display this usage message
560 -H hostname Hostname to connect to
563 The interpreter prints the result of string operations in the same way
564 as they are typed for input: inside quotes, and with quotes and other
565 funny characters escaped by backslashes, to show the precise
566 value. The string is enclosed in double quotes if the string contains
567 a single quote and no double quotes, else it's enclosed in single
568 quotes. (The
\keyword{print
} statement, described later, can be used
569 to write strings without quotes or escapes.)
571 Strings can be concatenated (glued together) with the
572 \code{+
} operator, and repeated with
\code{*
}:
575 >>> word = 'Help' + 'A'
578 >>> '<' + word*
5 + '>'
579 '<HelpAHelpAHelpAHelpAHelpA>'
582 Two string literals next to each other are automatically concatenated;
583 the first line above could also have been written
\samp{word = 'Help'
584 'A'
}; this only works with two literals, not with arbitrary string
589 >>> 'str' 'ing' # <- This is ok
591 >>> string.strip('str') + 'ing' # <- This is ok
593 >>> string.strip('str') 'ing' # <- This is invalid
594 File "<stdin>", line
1
595 string.strip('str') 'ing'
597 SyntaxError: invalid syntax
600 Strings can be subscripted (indexed); like in C, the first character
601 of a string has subscript (index)
0. There is no separate character
602 type; a character is simply a string of size one. Like in Icon,
603 substrings can be specified with the
\emph{slice notation
}: two indices
604 separated by a colon.
615 Unlike a C string, Python strings cannot be changed. Assigning to an
616 indexed position in the string results in an error:
620 Traceback (innermost last):
621 File "<stdin>", line
1, in ?
622 TypeError: object doesn't support item assignment
623 >>> word
[:-
1] = 'Splat'
624 Traceback (innermost last):
625 File "<stdin>", line
1, in ?
626 TypeError: object doesn't support slice assignment
629 However, creating a new string with the combined content is easy and
635 >>> 'Splat' + word
[-
1:
]
639 Slice indices have useful defaults; an omitted first index defaults to
640 zero, an omitted second index defaults to the size of the string being
644 >>> word
[:
2] # The first two characters
646 >>> word
[2:
] # All but the first two characters
650 Here's a useful invariant of slice operations:
651 \code{s
[:i
] + s
[i:
]} equals
\code{s
}.
654 >>> word
[:
2] + word
[2:
]
656 >>> word
[:
3] + word
[3:
]
660 Degenerate slice indices are handled gracefully: an index that is too
661 large is replaced by the string size, an upper bound smaller than the
662 lower bound returns an empty string.
673 Indices may be negative numbers, to start counting from the right.
677 >>> word
[-
1] # The last character
679 >>> word
[-
2] # The last-but-one character
681 >>> word
[-
2:
] # The last two characters
683 >>> word
[:-
2] # All but the last two characters
687 But note that -
0 is really the same as
0, so it does not count from
691 >>> word
[-
0] # (since -
0 equals
0)
695 Out-of-range negative slice indices are truncated, but don't try this
696 for single-element (non-slice) indices:
701 >>> word
[-
10] # error
702 Traceback (innermost last):
703 File "<stdin>", line
1
704 IndexError: string index out of range
707 The best way to remember how slices work is to think of the indices as
708 pointing
\emph{between
} characters, with the left edge of the first
709 character numbered
0. Then the right edge of the last character of a
710 string of
\var{n
} characters has index
\var{n
}, for example:
713 +---+---+---+---+---+
714 | H | e | l | p | A |
715 +---+---+---+---+---+
720 The first row of numbers gives the position of the indices
0..
.5 in
721 the string; the second row gives the corresponding negative indices.
722 The slice from
\var{i
} to
\var{j
} consists of all characters between
723 the edges labeled
\var{i
} and
\var{j
}, respectively.
725 For non-negative indices, the length of a slice is the difference of
726 the indices, if both are within bounds, e.g., the length of
727 \code{word
[1:
3]} is
2.
729 The built-in function
\function{len()
} returns the length of a string:
732 >>> s = 'supercalifragilisticexpialidocious'
738 \subsection{Unicode Strings
\label{unicodeStrings
}}
739 \sectionauthor{Marc-Andre Lemburg
}{mal@lemburg.com
}
741 Starting with Python
2.0 a new data type for storing text data is
742 available to the programmer: the Unicode object. It can be used to
743 store and manipulate Unicode data (see
\url{http://www.unicode.org
})
744 and integrates well with the existing string objects providing
745 auto-conversions where necessary.
747 Unicode has the advantage of providing one ordinal for every character
748 in every script used in modern and ancient texts. Previously, there
749 were only
256 possible ordinals for script characters and texts were
750 typically bound to a code page which mapped the ordinals to script
751 characters. This lead to very much confusion especially with respect
752 to internationalization (usually written as
\samp{i18n
} ---
753 \character{i
} +
18 characters +
\character{n
}) of software. Unicode
754 solves these problems by defining one code page for all scripts.
756 Creating Unicode strings in Python is just as simple as creating
764 The small
\character{u
} in front of the quote indicates that an
765 Unicode string is supposed to be created. If you want to include
766 special characters in the string, you can do so by using the Python
767 \emph{Unicode-Escape
} encoding. The following example shows how:
770 >>> u'Hello\
\u0020World !'
774 The escape sequence
\code{\
\u0020} indicates to insert the Unicode
775 character with the HEX ordinal
0x0020 (the space character) at the
778 Other characters are interpreted by using their respective ordinal
779 value directly as Unicode ordinal. Due to the fact that the lower
256
780 Unicode are the same as the standard Latin-
1 encoding used in many
781 western countries, the process of entering Unicode is greatly
784 For experts, there is also a raw mode just like for normal
785 strings. You have to prepend the string with a small 'r' to have
786 Python use the
\emph{Raw-Unicode-Escape
} encoding. It will only apply
787 the above
\code{\
\uXXXX} conversion if there is an uneven number of
788 backslashes in front of the small 'u'.
791 >>> ur'Hello
\u0020World !'
793 >>> ur'Hello\
\u0020World !'
794 u'Hello\\\
\u0020World !'
797 The raw mode is most useful when you have to enter lots of backslashes
798 e.g. in regular expressions.
800 Apart from these standard encodings, Python provides a whole set of
801 other ways of creating Unicode strings on the basis of a known
804 The builtin
\function{unicode()
}\bifuncindex{unicode
} provides access
805 to all registered Unicode codecs (COders and DECoders). Some of the
806 more well known encodings which these codecs can convert are
807 \emph{Latin-
1},
\emph{ASCII
},
\emph{UTF-
8} and
\emph{UTF-
16}. The latter two
808 are variable length encodings which permit to store Unicode characters
809 in
8 or
16 bits. Python uses UTF-
8 as default encoding. This becomes
810 noticeable when printing Unicode strings or writing them to files.
816 '
\303\244\303\266\303\274'
819 If you have data in a specific encoding and want to produce a
820 corresponding Unicode string from it, you can use the
821 \function{unicode()
} builtin with the encoding name as second
825 >>> unicode('
\303\244\303\266\303\274','UTF-
8')
829 To convert the Unicode string back into a string using the original
830 encoding, the objects provide an
\method{encode()
} method.
833 >>> u"äöü".encode('UTF-
8')
834 '
\303\244\303\266\303\274'
838 \subsection{Lists
\label{lists
}}
840 Python knows a number of
\emph{compound
} data types, used to group
841 together other values. The most versatile is the
\emph{list
}, which
842 can be written as a list of comma-separated values (items) between
843 square brackets. List items need not all have the same type.
846 >>> a =
['spam', 'eggs',
100,
1234]
848 ['spam', 'eggs',
100,
1234]
851 Like string indices, list indices start at
0, and lists can be sliced,
852 concatenated and so on:
863 >>> a
[:
2] +
['bacon',
2*
2]
864 ['spam', 'eggs', 'bacon',
4]
865 >>>
3*a
[:
3] +
['Boe!'
]
866 ['spam', 'eggs',
100, 'spam', 'eggs',
100, 'spam', 'eggs',
100, 'Boe!'
]
869 Unlike strings, which are
\emph{immutable
}, it is possible to change
870 individual elements of a list:
874 ['spam', 'eggs',
100,
1234]
877 ['spam', 'eggs',
123,
1234]
880 Assignment to slices is also possible, and this can even change the size
884 >>> # Replace some items:
893 ... a
[1:
1] =
['bletch', 'xyzzy'
]
895 [123, 'bletch', 'xyzzy',
1234]
896 >>> a
[:
0] = a # Insert (a copy of) itself at the beginning
898 [123, 'bletch', 'xyzzy',
1234,
123, 'bletch', 'xyzzy',
1234]
901 The built-in function
\function{len()
} also applies to lists:
908 It is possible to nest lists (create lists containing other lists),
920 >>> p
[1].append('xtra') # See section
5.1
922 [1,
[2,
3, 'xtra'
],
4]
927 Note that in the last example,
\code{p
[1]} and
\code{q
} really refer to
928 the same object! We'll come back to
\emph{object semantics
} later.
930 \section{First Steps Towards Programming
\label{firstSteps
}}
932 Of course, we can use Python for more complicated tasks than adding
933 two and two together. For instance, we can write an initial
934 subsequence of the
\emph{Fibonacci
} series as follows:
937 >>> # Fibonacci series:
938 ... # the sum of two elements defines the next
952 This example introduces several new features.
957 The first line contains a
\emph{multiple assignment
}: the variables
958 \code{a
} and
\code{b
} simultaneously get the new values
0 and
1. On the
959 last line this is used again, demonstrating that the expressions on
960 the right-hand side are all evaluated first before any of the
961 assignments take place. The right-hand side expressions are evaluated
962 from the left to the right.
965 The
\keyword{while
} loop executes as long as the condition (here:
966 \code{b <
10}) remains true. In Python, like in C, any non-zero
967 integer value is true; zero is false. The condition may also be a
968 string or list value, in fact any sequence; anything with a non-zero
969 length is true, empty sequences are false. The test used in the
970 example is a simple comparison. The standard comparison operators are
971 written the same as in C:
\code{<
} (less than),
\code{>
} (greater than),
972 \code{==
} (equal to),
\code{<=
} (less than or equal to),
973 \code{>=
} (greater than or equal to) and
\code{!=
} (not equal to).
976 The
\emph{body
} of the loop is
\emph{indented
}: indentation is Python's
977 way of grouping statements. Python does not (yet!) provide an
978 intelligent input line editing facility, so you have to type a tab or
979 space(s) for each indented line. In practice you will prepare more
980 complicated input for Python with a text editor; most text editors have
981 an auto-indent facility. When a compound statement is entered
982 interactively, it must be followed by a blank line to indicate
983 completion (since the parser cannot guess when you have typed the last
984 line). Note that each line within a basic block must be indented by
988 The
\keyword{print
} statement writes the value of the expression(s) it is
989 given. It differs from just writing the expression you want to write
990 (as we did earlier in the calculator examples) in the way it handles
991 multiple expressions and strings. Strings are printed without quotes,
992 and a space is inserted between items, so you can format things nicely,
997 >>> print 'The value of i is', i
998 The value of i is
65536
1001 A trailing comma avoids the newline after the output:
1009 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1012 Note that the interpreter inserts a newline before it prints the next
1013 prompt if the last line was not completed.
1018 \chapter{More Control Flow Tools
\label{moreControl
}}
1020 Besides the
\keyword{while
} statement just introduced, Python knows
1021 the usual control flow statements known from other languages, with
1024 \section{\keyword{if
} Statements
\label{if
}}
1026 Perhaps the most well-known statement type is the
1027 \keyword{if
} statement. For example:
1030 >>> x = int(raw_input("Please enter a number: "))
1033 ... print 'Negative changed to zero'
1043 There can be zero or more
\keyword{elif
} parts, and the
1044 \keyword{else
} part is optional. The keyword `
\keyword{elif
}' is
1045 short for `else if', and is useful to avoid excessive indentation. An
1046 \keyword{if
} \ldots\
\keyword{elif
} \ldots\
\keyword{elif
} \ldots\ sequence
1047 % Weird spacings happen here if the wrapping of the source text
1048 % gets changed in the wrong way.
1049 is a substitute for the
\emph{switch
} or
1050 \emph{case
} statements found in other languages.
1053 \section{\keyword{for
} Statements
\label{for
}}
1055 The
\keyword{for
}\stindex{for
} statement in Python differs a bit from
1056 what you may be used to in C or Pascal. Rather than always
1057 iterating over an arithmetic progression of numbers (like in Pascal),
1058 or giving the user the ability to define both the iteration step and
1059 halting condition (as C), Python's
1060 \keyword{for
}\stindex{for
} statement iterates over the items of any
1061 sequence (e.g., a list or a string), in the order that they appear in
1062 the sequence. For example (no pun intended):
1063 % One suggestion was to give a real C example here, but that may only
1064 % serve to confuse non-C programmers.
1067 >>> # Measure some strings:
1068 ... a =
['cat', 'window', 'defenestrate'
]
1077 It is not safe to modify the sequence being iterated over in the loop
1078 (this can only happen for mutable sequence types, i.e., lists). If
1079 you need to modify the list you are iterating over, e.g., duplicate
1080 selected items, you must iterate over a copy. The slice notation
1081 makes this particularly convenient:
1084 >>> for x in a
[:
]: # make a slice copy of the entire list
1085 ... if len(x) >
6: a.insert(
0, x)
1088 ['defenestrate', 'cat', 'window', 'defenestrate'
]
1092 \section{The
\function{range()
} Function
\label{range
}}
1094 If you do need to iterate over a sequence of numbers, the built-in
1095 function
\function{range()
} comes in handy. It generates lists
1096 containing arithmetic progressions, e.g.:
1100 [0,
1,
2,
3,
4,
5,
6,
7,
8,
9]
1103 The given end point is never part of the generated list;
1104 \code{range(
10)
} generates a list of
10 values, exactly the legal
1105 indices for items of a sequence of length
10. It is possible to let
1106 the range start at another number, or to specify a different increment
1107 (even negative; sometimes this is called the `step'):
1114 >>> range(-
10, -
100, -
30)
1118 To iterate over the indices of a sequence, combine
1119 \function{range()
} and
\function{len()
} as follows:
1122 >>> a =
['Mary', 'had', 'a', 'little', 'lamb'
]
1123 >>> for i in range(len(a)):
1134 \section{\keyword{break
} and
\keyword{continue
} Statements, and
1135 \keyword{else
} Clauses on Loops
1138 The
\keyword{break
} statement, like in C, breaks out of the smallest
1139 enclosing
\keyword{for
} or
\keyword{while
} loop.
1141 The
\keyword{continue
} statement, also borrowed from C, continues
1142 with the next iteration of the loop.
1144 Loop statements may have an
\code{else
} clause; it is executed when
1145 the loop terminates through exhaustion of the list (with
1146 \keyword{for
}) or when the condition becomes false (with
1147 \keyword{while
}), but not when the loop is terminated by a
1148 \keyword{break
} statement. This is exemplified by the following loop,
1149 which searches for prime numbers:
1152 >>> for n in range(
2,
10):
1153 ... for x in range(
2, n):
1155 ... print n, 'equals', x, '*', n/x
1158 ... print n, 'is a prime number'
1171 \section{\keyword{pass
} Statements
\label{pass
}}
1173 The
\keyword{pass
} statement does nothing.
1174 It can be used when a statement is required syntactically but the
1175 program requires no action.
1180 ... pass # Busy-wait for keyboard interrupt
1185 \section{Defining Functions
\label{functions
}}
1187 We can create a function that writes the Fibonacci series to an
1191 >>> def fib(n): # write Fibonacci series up to n
1192 ... "Print a Fibonacci series up to n"
1198 >>> # Now call the function we just defined:
1200 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
1203 The keyword
\keyword{def
} introduces a function
\emph{definition
}. It
1204 must be followed by the function name and the parenthesized list of
1205 formal parameters. The statements that form the body of the function
1206 start at the next line, and must be indented. The first statement of
1207 the function body can optionally be a string literal; this string
1208 literal is the function's
\index{documentation strings
}documentation
1209 string, or
\dfn{docstring
}.
\index{docstrings
}\index{strings, documentation
}
1211 There are tools which use docstrings to automatically produce online
1212 or printed documentation, or to let the user interactively browse
1213 through code; it's good practice to include docstrings in code that
1214 you write, so try to make a habit of it.
1216 The
\emph{execution
} of a function introduces a new symbol table used
1217 for the local variables of the function. More precisely, all variable
1218 assignments in a function store the value in the local symbol table;
1219 whereas variable references first look in the local symbol table, then
1220 in the global symbol table, and then in the table of built-in names.
1221 Thus, global variables cannot be directly assigned a value within a
1222 function (unless named in a
\keyword{global
} statement), although
1223 they may be referenced.
1225 The actual parameters (arguments) to a function call are introduced in
1226 the local symbol table of the called function when it is called; thus,
1227 arguments are passed using
\emph{call by value
} (where the
1228 \emph{value
} is always an object
\emph{reference
}, not the value of
1229 the object).
\footnote{
1230 Actually,
\emph{call by object reference
} would be a better
1231 description, since if a mutable object is passed, the caller
1232 will see any changes the callee makes to it (e.g., items
1233 inserted into a list).
1234 } When a function calls another function, a new local symbol table is
1235 created for that call.
1237 A function definition introduces the function name in the current
1238 symbol table. The value of the function name
1239 has a type that is recognized by the interpreter as a user-defined
1240 function. This value can be assigned to another name which can then
1241 also be used as a function. This serves as a general renaming
1246 <function object at
10042ed0>
1249 1 1 2 3 5 8 13 21 34 55 89
1252 You might object that
\code{fib
} is not a function but a procedure. In
1253 Python, like in C, procedures are just functions that don't return a
1254 value. In fact, technically speaking, procedures do return a value,
1255 albeit a rather boring one. This value is called
\code{None
} (it's a
1256 built-in name). Writing the value
\code{None
} is normally suppressed by
1257 the interpreter if it would be the only value written. You can see it
1258 if you really want to:
1265 It is simple to write a function that returns a list of the numbers of
1266 the Fibonacci series, instead of printing it:
1269 >>> def fib2(n): # return Fibonacci series up to n
1270 ... "Return a list containing the Fibonacci series up to n"
1274 ... result.append(b) # see below
1278 >>> f100 = fib2(
100) # call it
1279 >>> f100 # write the result
1280 [1,
1,
2,
3,
5,
8,
13,
21,
34,
55,
89]
1283 This example, as usual, demonstrates some new Python features:
1288 The
\keyword{return
} statement returns with a value from a function.
1289 \keyword{return
} without an expression argument is used to return from
1290 the middle of a procedure (falling off the end also returns from a
1291 procedure), in which case the
\code{None
} value is returned.
1294 The statement
\code{result.append(b)
} calls a
\emph{method
} of the list
1295 object
\code{result
}. A method is a function that `belongs' to an
1296 object and is named
\code{obj.methodname
}, where
\code{obj
} is some
1297 object (this may be an expression), and
\code{methodname
} is the name
1298 of a method that is defined by the object's type. Different types
1299 define different methods. Methods of different types may have the
1300 same name without causing ambiguity. (It is possible to define your
1301 own object types and methods, using
\emph{classes
}, as discussed later
1303 The method
\method{append()
} shown in the example, is defined for
1304 list objects; it adds a new element at the end of the list. In this
1305 example it is equivalent to
\samp{result = result +
[b
]}, but more
1310 \section{More on Defining Functions
\label{defining
}}
1312 It is also possible to define functions with a variable number of
1313 arguments. There are three forms, which can be combined.
1315 \subsection{Default Argument Values
\label{defaultArgs
}}
1317 The most useful form is to specify a default value for one or more
1318 arguments. This creates a function that can be called with fewer
1319 arguments than it is defined, e.g.
1322 def ask_ok(prompt, retries=
4, complaint='Yes or no, please!'):
1324 ok = raw_input(prompt)
1325 if ok in ('y', 'ye', 'yes'): return
1
1326 if ok in ('n', 'no', 'nop', 'nope'): return
0
1327 retries = retries -
1
1328 if retries <
0: raise IOError, 'refusenik user'
1332 This function can be called either like this:
1333 \code{ask_ok('Do you really want to quit?')
} or like this:
1334 \code{ask_ok('OK to overwrite the file?',
2)
}.
1336 The default values are evaluated at the point of function definition
1337 in the
\emph{defining
} scope, so that e.g.
1341 def f(arg = i): print arg
1346 will print
\code{5}.
1348 \strong{Important warning:
} The default value is evaluated only once.
1349 This makes a difference when the default is a mutable object such as a
1350 list or dictionary. For example, the following function accumulates
1351 the arguments passed to it on subsequent calls:
1370 If you don't want the default to be shared between subsequent calls,
1371 you can write the function like this instead:
1381 \subsection{Keyword Arguments
\label{keywordArgs
}}
1383 Functions can also be called using
1384 keyword arguments of the form
\samp{\var{keyword
} =
\var{value
}}. For
1385 instance, the following function:
1388 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1389 print "-- This parrot wouldn't", action,
1390 print "if you put", voltage, "Volts through it."
1391 print "-- Lovely plumage, the", type
1392 print "-- It's", state, "!"
1395 could be called in any of the following ways:
1399 parrot(action = 'VOOOOOM', voltage =
1000000)
1400 parrot('a thousand', state = 'pushing up the daisies')
1401 parrot('a million', 'bereft of life', 'jump')
1404 but the following calls would all be invalid:
1407 parrot() # required argument missing
1408 parrot(voltage=
5.0, 'dead') # non-keyword argument following keyword
1409 parrot(
110, voltage=
220) # duplicate value for argument
1410 parrot(actor='John Cleese') # unknown keyword
1413 In general, an argument list must have any positional arguments
1414 followed by any keyword arguments, where the keywords must be chosen
1415 from the formal parameter names. It's not important whether a formal
1416 parameter has a default value or not. No argument may receive a
1417 value more than once --- formal parameter names corresponding to
1418 positional arguments cannot be used as keywords in the same calls.
1419 Here's an example that fails due to this restriction:
1422 >>> def function(a):
1425 >>> function(
0, a=
0)
1426 Traceback (innermost last):
1427 File "<stdin>", line
1, in ?
1428 TypeError: keyword parameter redefined
1431 When a final formal parameter of the form
\code{**
\var{name
}} is
1432 present, it receives a dictionary containing all keyword arguments
1433 whose keyword doesn't correspond to a formal parameter. This may be
1434 combined with a formal parameter of the form
1435 \code{*
\var{name
}} (described in the next subsection) which receives a
1436 tuple containing the positional arguments beyond the formal parameter
1437 list. (
\code{*
\var{name
}} must occur before
\code{**
\var{name
}}.)
1438 For example, if we define a function like this:
1441 def cheeseshop(kind, *arguments, **keywords):
1442 print "-- Do you have any", kind, '?'
1443 print "-- I'm sorry, we're all out of", kind
1444 for arg in arguments: print arg
1446 for kw in keywords.keys(): print kw, ':', keywords
[kw
]
1449 It could be called like this:
1452 cheeseshop('Limburger', "It's very runny, sir.",
1453 "It's really very, VERY runny, sir.",
1454 client='John Cleese',
1455 shopkeeper='Michael Palin',
1456 sketch='Cheese Shop Sketch')
1459 and of course it would print:
1462 -- Do you have any Limburger ?
1463 -- I'm sorry, we're all out of Limburger
1464 It's very runny, sir.
1465 It's really very, VERY runny, sir.
1466 ----------------------------------------
1467 client : John Cleese
1468 shopkeeper : Michael Palin
1469 sketch : Cheese Shop Sketch
1473 \subsection{Arbitrary Argument Lists
\label{arbitraryArgs
}}
1475 Finally, the least frequently used option is to specify that a
1476 function can be called with an arbitrary number of arguments. These
1477 arguments will be wrapped up in a tuple. Before the variable number
1478 of arguments, zero or more normal arguments may occur.
1481 def fprintf(file, format, *args):
1482 file.write(format
% args)
1486 \subsection{Lambda Forms
\label{lambda
}}
1488 By popular demand, a few features commonly found in functional
1489 programming languages and Lisp have been added to Python. With the
1490 \keyword{lambda
} keyword, small anonymous functions can be created.
1491 Here's a function that returns the sum of its two arguments:
1492 \samp{lambda a, b: a+b
}. Lambda forms can be used wherever function
1493 objects are required. They are syntactically restricted to a single
1494 expression. Semantically, they are just syntactic sugar for a normal
1495 function definition. Like nested function definitions, lambda forms
1496 cannot reference variables from the containing scope, but this can be
1497 overcome through the judicious use of default argument values, e.g.
1500 def make_incrementor(n):
1501 return lambda x, incr=n: x+incr
1505 \subsection{Documentation Strings
\label{docstrings
}}
1507 There are emerging conventions about the content and formatting of
1508 documentation strings.
1509 \index{docstrings
}\index{documentation strings
}
1510 \index{strings, documentation
}
1512 The first line should always be a short, concise summary of the
1513 object's purpose. For brevity, it should not explicitly state the
1514 object's name or type, since these are available by other means
1515 (except if the name happens to be a verb describing a function's
1516 operation). This line should begin with a capital letter and end with
1519 If there are more lines in the documentation string, the second line
1520 should be blank, visually separating the summary from the rest of the
1521 description. The following lines should be one or more paragraphs
1522 describing the object's calling conventions, its side effects, etc.
1524 The Python parser does not strip indentation from multi-line string
1525 literals in Python, so tools that process documentation have to strip
1526 indentation if desired. This is done using the following convention.
1527 The first non-blank line
\emph{after
} the first line of the string
1528 determines the amount of indentation for the entire documentation
1529 string. (We can't use the first line since it is generally adjacent
1530 to the string's opening quotes so its indentation is not apparent in
1531 the string literal.) Whitespace ``equivalent'' to this indentation is
1532 then stripped from the start of all lines of the string. Lines that
1533 are indented less should not occur, but if they occur all their
1534 leading whitespace should be stripped. Equivalence of whitespace
1535 should be tested after expansion of tabs (to
8 spaces, normally).
1537 Here is an example of a multi-line docstring:
1540 >>> def my_function():
1541 ... """Do nothing, but
document it.
1543 ... No, really, it doesn't do anything.
1547 >>> print my_function.__doc__
1548 Do nothing, but
document it.
1550 No, really, it doesn't do anything.
1556 \chapter{Data Structures
\label{structures
}}
1558 This chapter describes some things you've learned about already in
1559 more detail, and adds some new things as well.
1562 \section{More on Lists
\label{moreLists
}}
1564 The list data type has some more methods. Here are all of the methods
1569 \item[\code{append(x)
}]
1570 Add an item to the end of the list;
1571 equivalent to
\code{a
[len(a):
] =
[x
]}.
1573 \item[\code{extend(L)
}]
1574 Extend the list by appending all the items in the given list;
1575 equivalent to
\code{a
[len(a):
] = L
}.
1577 \item[\code{insert(i, x)
}]
1578 Insert an item at a given position. The first argument is the index of
1579 the element before which to insert, so
\code{a.insert(
0, x)
} inserts at
1580 the front of the list, and
\code{a.insert(len(a), x)
} is equivalent to
1583 \item[\code{remove(x)
}]
1584 Remove the first item from the list whose value is
\code{x
}.
1585 It is an error if there is no such item.
1587 \item[\code{pop(
\optional{i
})
}]
1588 Remove the item at the given position in the list, and return it. If
1589 no index is specified,
\code{a.pop()
} returns the last item in the
1590 list. The item is also removed from the list.
1592 \item[\code{index(x)
}]
1593 Return the index in the list of the first item whose value is
\code{x
}.
1594 It is an error if there is no such item.
1596 \item[\code{count(x)
}]
1597 Return the number of times
\code{x
} appears in the list.
1599 \item[\code{sort()
}]
1600 Sort the items of the list, in place.
1602 \item[\code{reverse()
}]
1603 Reverse the elements of the list, in place.
1607 An example that uses most of the list methods:
1610 >>> a =
[66.6,
333,
333,
1,
1234.5]
1611 >>> print a.count(
333), a.count(
66.6), a.count('x')
1616 [66.6,
333, -
1,
333,
1,
1234.5,
333]
1621 [66.6, -
1,
333,
1,
1234.5,
333]
1624 [333,
1234.5,
1,
333, -
1,
66.6]
1627 [-
1,
1,
66.6,
333,
333,
1234.5]
1631 \subsection{Using Lists as Stacks
\label{lists-as-stacks
}}
1632 \sectionauthor{Ka-Ping Yee
}{ping@lfs.org
}
1634 The list methods make it very easy to use a list as a stack, where the
1635 last element added is the first element retrieved (``last-in,
1636 first-out''). To add an item to the top of the stack, use
1637 \method{append()
}. To retrieve an item from the top of the stack, use
1638 \method{pop()
} without an explicit index. For example:
1641 >>> stack =
[3,
4,
5]
1659 \subsection{Using Lists as Queues
\label{lists-as-queues
}}
1660 \sectionauthor{Ka-Ping Yee
}{ping@lfs.org
}
1662 You can also use a list conveniently as a queue, where the first
1663 element added is the first element retrieved (``first-in,
1664 first-out''). To add an item to the back of the queue, use
1665 \method{append()
}. To retrieve an item from the front of the queue,
1666 use
\method{pop()
} with
\code{0} as the index. For example:
1669 >>> queue =
["Eric", "John", "Michael"
]
1670 >>> queue.append("Terry") # Terry arrives
1671 >>> queue.append("Graham") # Graham arrives
1677 ['Michael', 'Terry', 'Graham'
]
1681 \subsection{Functional Programming Tools
\label{functional
}}
1683 There are three built-in functions that are very useful when used with
1684 lists:
\function{filter()
},
\function{map()
}, and
\function{reduce()
}.
1686 \samp{filter(
\var{function
},
\var{sequence
})
} returns a sequence (of
1687 the same type, if possible) consisting of those items from the
1688 sequence for which
\code{\var{function
}(
\var{item
})
} is true. For
1689 example, to compute some primes:
1692 >>> def f(x): return x
% 2 != 0 and x % 3 != 0
1694 >>> filter(f, range(
2,
25))
1695 [5,
7,
11,
13,
17,
19,
23]
1698 \samp{map(
\var{function
},
\var{sequence
})
} calls
1699 \code{\var{function
}(
\var{item
})
} for each of the sequence's items and
1700 returns a list of the return values. For example, to compute some
1704 >>> def cube(x): return x*x*x
1706 >>> map(cube, range(
1,
11))
1707 [1,
8,
27,
64,
125,
216,
343,
512,
729,
1000]
1710 More than one sequence may be passed; the function must then have as
1711 many arguments as there are sequences and is called with the
1712 corresponding item from each sequence (or
\code{None
} if some sequence
1713 is shorter than another). If
\code{None
} is passed for the function,
1714 a function returning its argument(s) is substituted.
1716 Combining these two special cases, we see that
1717 \samp{map(None,
\var{list1
},
\var{list2
})
} is a convenient way of
1718 turning a pair of lists into a list of pairs. For example:
1722 >>> def square(x): return x*x
1724 >>> map(None, seq, map(square, seq))
1725 [(
0,
0), (
1,
1), (
2,
4), (
3,
9), (
4,
16), (
5,
25), (
6,
36), (
7,
49)
]
1728 \samp{reduce(
\var{func
},
\var{sequence
})
} returns a single value
1729 constructed by calling the binary function
\var{func
} on the first two
1730 items of the sequence, then on the result and the next item, and so
1731 on. For example, to compute the sum of the numbers
1 through
10:
1734 >>> def add(x,y): return x+y
1736 >>> reduce(add, range(
1,
11))
1740 If there's only one item in the sequence, its value is returned; if
1741 the sequence is empty, an exception is raised.
1743 A third argument can be passed to indicate the starting value. In this
1744 case the starting value is returned for an empty sequence, and the
1745 function is first applied to the starting value and the first sequence
1746 item, then to the result and the next item, and so on. For example,
1750 ... def add(x,y): return x+y
1751 ... return reduce(add, seq,
0)
1753 >>> sum(range(
1,
11))
1760 \subsection{List Comprehensions
}
1762 List comprehensions provide a concise way to create lists without resorting
1763 to use of
\function{map()
},
\function{filter()
} and/or
\keyword{lambda
}.
1764 The resulting list definition tends often to be clearer than lists built
1765 using those constructs. Each list comprehension consists of an expression
1766 following by a
\keyword{for
} clause, then zero or more
\keyword{for
} or
1767 \keyword{if
} clauses. The result will be a list resulting from evaluating
1768 the expression in the context of the
\keyword{for
} and
\keyword{if
} clauses
1769 which follow it. If the expression would evaluate to a tuple, it must be
1773 >>> freshfruit =
[' banana', ' loganberry ', 'passion fruit '
]
1774 >>>
[weapon.strip() for weapon in freshfruit
]
1775 ['banana', 'loganberry', 'passion fruit'
]
1777 >>>
[3*x for x in vec
]
1779 >>>
[3*x for x in vec if x >
3]
1781 >>>
[3*x for x in vec if x <
2]
1783 >>>
[{x: x**
2} for x in vec
]
1784 [{2:
4},
{4:
16},
{6:
36}]
1785 >>>
[[x,x**
2] for x in vec
]
1786 [[2,
4],
[4,
16],
[6,
36]]
1787 >>>
[x, x**
2 for x in vec
] # error - parens required for tuples
1788 File "<stdin>", line
1
1789 [x, x**
2 for x in vec
]
1791 SyntaxError: invalid syntax
1792 >>>
[(x, x**
2) for x in vec
]
1793 [(
2,
4), (
4,
16), (
6,
36)
]
1794 >>> vec1 =
[2,
4,
6]
1795 >>> vec2 =
[4,
3, -
9]
1796 >>>
[x*y for x in vec1 for y in vec2
]
1797 [8,
6, -
18,
16,
12, -
36,
24,
18, -
54]
1798 >>>
[x+y for x in vec1 for y in vec2
]
1799 [6,
5, -
7,
8,
7, -
5,
10,
9, -
3]
1803 \section{The
\keyword{del
} statement
\label{del
}}
1805 There is a way to remove an item from a list given its index instead
1806 of its value: the
\keyword{del
} statement. This can also be used to
1807 remove slices from a list (which we did earlier by assignment of an
1808 empty list to the slice). For example:
1812 [-
1,
1,
66.6,
333,
333,
1234.5]
1815 [1,
66.6,
333,
333,
1234.5]
1821 \keyword{del
} can also be used to delete entire variables:
1827 Referencing the name
\code{a
} hereafter is an error (at least until
1828 another value is assigned to it). We'll find other uses for
1829 \keyword{del
} later.
1832 \section{Tuples and Sequences
\label{tuples
}}
1834 We saw that lists and strings have many common properties, e.g.,
1835 indexing and slicing operations. They are two examples of
1836 \emph{sequence
} data types. Since Python is an evolving language,
1837 other sequence data types may be added. There is also another
1838 standard sequence data type: the
\emph{tuple
}.
1840 A tuple consists of a number of values separated by commas, for
1844 >>> t =
12345,
54321, 'hello!'
1848 (
12345,
54321, 'hello!')
1849 >>> # Tuples may be nested:
1850 ... u = t, (
1,
2,
3,
4,
5)
1852 ((
12345,
54321, 'hello!'), (
1,
2,
3,
4,
5))
1855 As you see, on output tuples are alway enclosed in parentheses, so
1856 that nested tuples are interpreted correctly; they may be input with
1857 or without surrounding parentheses, although often parentheses are
1858 necessary anyway (if the tuple is part of a larger expression).
1860 Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1861 from a database, etc. Tuples, like strings, are immutable: it is not
1862 possible to assign to the individual items of a tuple (you can
1863 simulate much of the same effect with slicing and concatenation,
1864 though). It is also possible to create tuples which contain mutable
1865 objects, such as lists.
1867 A special problem is the construction of tuples containing
0 or
1
1868 items: the syntax has some extra quirks to accommodate these. Empty
1869 tuples are constructed by an empty pair of parentheses; a tuple with
1870 one item is constructed by following a value with a comma
1871 (it is not sufficient to enclose a single value in parentheses).
1872 Ugly, but effective. For example:
1876 >>> singleton = 'hello', # <-- note trailing comma
1885 The statement
\code{t =
12345,
54321, 'hello!'
} is an example of
1886 \emph{tuple packing
}: the values
\code{12345},
\code{54321} and
1887 \code{'hello!'
} are packed together in a tuple. The reverse operation
1888 is also possible, e.g.:
1894 This is called, appropriately enough,
\emph{sequence unpacking
}.
1895 Sequence unpacking requires that the list of variables on the left
1896 have the same number of elements as the length of the sequence. Note
1897 that multiple assignment is really just a combination of tuple packing
1898 and sequence unpacking!
1900 There is a small bit of asymmetry here: packing multiple values
1901 always creates a tuple, and unpacking works for any sequence.
1903 % XXX Add a bit on the difference between tuples and lists.
1906 \section{Dictionaries
\label{dictionaries
}}
1908 Another useful data type built into Python is the
\emph{dictionary
}.
1909 Dictionaries are sometimes found in other languages as ``associative
1910 memories'' or ``associative arrays''. Unlike sequences, which are
1911 indexed by a range of numbers, dictionaries are indexed by
\emph{keys
},
1912 which can be any immutable type; strings and numbers can always be
1913 keys. Tuples can be used as keys if they contain only strings,
1914 numbers, or tuples; if a tuple contains any mutable object either
1915 directly or indirectly, it cannot be used as a key. You can't use
1916 lists as keys, since lists can be modified in place using their
1917 \method{append()
} and
\method{extend()
} methods, as well as slice and
1918 indexed assignments.
1920 It is best to think of a dictionary as an unordered set of
1921 \emph{key: value
} pairs, with the requirement that the keys are unique
1922 (within one dictionary).
1923 A pair of braces creates an empty dictionary:
\code{\
{\
}}.
1924 Placing a comma-separated list of key:value pairs within the
1925 braces adds initial key:value pairs to the dictionary; this is also the
1926 way dictionaries are written on output.
1928 The main operations on a dictionary are storing a value with some key
1929 and extracting the value given the key. It is also possible to delete
1932 If you store using a key that is already in use, the old value
1933 associated with that key is forgotten. It is an error to extract a
1934 value using a non-existent key.
1936 The
\code{keys()
} method of a dictionary object returns a list of all
1937 the keys used in the dictionary, in random order (if you want it
1938 sorted, just apply the
\code{sort()
} method to the list of keys). To
1939 check whether a single key is in the dictionary, use the
1940 \code{has_key()
} method of the dictionary.
1942 Here is a small example using a dictionary:
1945 >>> tel =
{'jack':
4098, 'sape':
4139}
1946 >>> tel
['guido'
] =
4127
1948 {'sape':
4139, 'guido':
4127, 'jack':
4098}
1952 >>> tel
['irv'
] =
4127
1954 {'guido':
4127, 'irv':
4127, 'jack':
4098}
1956 ['guido', 'irv', 'jack'
]
1957 >>> tel.has_key('guido')
1961 \section{More on Conditions
\label{conditions
}}
1963 The conditions used in
\code{while
} and
\code{if
} statements above can
1964 contain other operators besides comparisons.
1966 The comparison operators
\code{in
} and
\code{not in
} check whether a value
1967 occurs (does not occur) in a sequence. The operators
\code{is
} and
1968 \code{is not
} compare whether two objects are really the same object; this
1969 only matters for mutable objects like lists. All comparison operators
1970 have the same priority, which is lower than that of all numerical
1973 Comparisons can be chained: e.g.,
\code{a < b == c
} tests whether
1974 \code{a
} is less than
\code{b
} and moreover
\code{b
} equals
\code{c
}.
1976 Comparisons may be combined by the Boolean operators
\code{and
} and
1977 \code{or
}, and the outcome of a comparison (or of any other Boolean
1978 expression) may be negated with
\code{not
}. These all have lower
1979 priorities than comparison operators again; between them,
\code{not
} has
1980 the highest priority, and
\code{or
} the lowest, so that
1981 \code{A and not B or C
} is equivalent to
\code{(A and (not B)) or C
}. Of
1982 course, parentheses can be used to express the desired composition.
1984 The Boolean operators
\code{and
} and
\code{or
} are so-called
1985 \emph{shortcut
} operators: their arguments are evaluated from left to
1986 right, and evaluation stops as soon as the outcome is determined.
1987 E.g., if
\code{A
} and
\code{C
} are true but
\code{B
} is false,
\code{A
1988 and B and C
} does not evaluate the expression C. In general, the
1989 return value of a shortcut operator, when used as a general value and
1990 not as a Boolean, is the last evaluated argument.
1992 It is possible to assign the result of a comparison or other Boolean
1993 expression to a variable. For example,
1996 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1997 >>> non_null = string1 or string2 or string3
2002 Note that in Python, unlike C, assignment cannot occur inside expressions.
2003 C programmers may grumble about this, but it avoids a common class of
2004 problems encountered in C programs: typing
\code{=
} in an expression when
2005 \code{==
} was intended.
2008 \section{Comparing Sequences and Other Types
\label{comparing
}}
2010 Sequence objects may be compared to other objects with the same
2011 sequence type. The comparison uses
\emph{lexicographical
} ordering:
2012 first the first two items are compared, and if they differ this
2013 determines the outcome of the comparison; if they are equal, the next
2014 two items are compared, and so on, until either sequence is exhausted.
2015 If two items to be compared are themselves sequences of the same type,
2016 the lexicographical comparison is carried out recursively. If all
2017 items of two sequences compare equal, the sequences are considered
2018 equal. If one sequence is an initial subsequence of the other, the
2019 shorted sequence is the smaller one. Lexicographical ordering for
2020 strings uses the
\ASCII{} ordering for individual characters. Some
2021 examples of comparisons between sequences with the same types:
2024 (
1,
2,
3) < (
1,
2,
4)
2025 [1,
2,
3] <
[1,
2,
4]
2026 'ABC' < 'C' < 'Pascal' < 'Python'
2027 (
1,
2,
3,
4) < (
1,
2,
4)
2029 (
1,
2,
3) == (
1.0,
2.0,
3.0)
2030 (
1,
2, ('aa', 'ab')) < (
1,
2, ('abc', 'a'),
4)
2033 Note that comparing objects of different types is legal. The outcome
2034 is deterministic but arbitrary: the types are ordered by their name.
2035 Thus, a list is always smaller than a string, a string is always
2036 smaller than a tuple, etc. Mixed numeric types are compared according
2037 to their numeric value, so
0 equals
0.0, etc.
\footnote{
2038 The rules for comparing objects of different types should
2039 not be relied upon; they may change in a future version of
2044 \chapter{Modules
\label{modules
}}
2046 If you quit from the Python interpreter and enter it again, the
2047 definitions you have made (functions and variables) are lost.
2048 Therefore, if you want to write a somewhat longer program, you are
2049 better off using a text editor to prepare the input for the interpreter
2050 and running it with that file as input instead. This is known as creating a
2051 \emph{script
}. As your program gets longer, you may want to split it
2052 into several files for easier maintenance. You may also want to use a
2053 handy function that you've written in several programs without copying
2054 its definition into each program.
2056 To support this, Python has a way to put definitions in a file and use
2057 them in a script or in an interactive instance of the interpreter.
2058 Such a file is called a
\emph{module
}; definitions from a module can be
2059 \emph{imported
} into other modules or into the
\emph{main
} module (the
2060 collection of variables that you have access to in a script
2061 executed at the top level
2062 and in calculator mode).
2064 A module is a file containing Python definitions and statements. The
2065 file name is the module name with the suffix
\file{.py
} appended. Within
2066 a module, the module's name (as a string) is available as the value of
2067 the global variable
\code{__name__
}. For instance, use your favorite text
2068 editor to create a file called
\file{fibo.py
} in the current directory
2069 with the following contents:
2072 # Fibonacci numbers module
2074 def fib(n): # write Fibonacci series up to n
2080 def fib2(n): # return Fibonacci series up to n
2089 Now enter the Python interpreter and import this module with the
2096 This does not enter the names of the functions defined in
\code{fibo
}
2097 directly in the current symbol table; it only enters the module name
2099 Using the module name you can access the functions:
2103 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
2105 [1,
1,
2,
3,
5,
8,
13,
21,
34,
55,
89]
2110 If you intend to use a function often you can assign it to a local name:
2115 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2119 \section{More on Modules
\label{moreModules
}}
2121 A module can contain executable statements as well as function
2123 These statements are intended to initialize the module.
2124 They are executed only the
2125 \emph{first
} time the module is imported somewhere.
\footnote{
2126 In fact function definitions are also `statements' that are
2127 `executed'; the execution enters the function name in the
2128 module's global symbol table.
2131 Each module has its own private symbol table, which is used as the
2132 global symbol table by all functions defined in the module.
2133 Thus, the author of a module can use global variables in the module
2134 without worrying about accidental clashes with a user's global
2136 On the other hand, if you know what you are doing you can touch a
2137 module's global variables with the same notation used to refer to its
2139 \code{modname.itemname
}.
2141 Modules can import other modules. It is customary but not required to
2142 place all
\keyword{import
} statements at the beginning of a module (or
2143 script, for that matter). The imported module names are placed in the
2144 importing module's global symbol table.
2146 There is a variant of the
\keyword{import
} statement that imports
2147 names from a module directly into the importing module's symbol
2151 >>> from fibo import fib, fib2
2153 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2156 This does not introduce the module name from which the imports are taken
2157 in the local symbol table (so in the example,
\code{fibo
} is not
2160 There is even a variant to import all names that a module defines:
2163 >>> from fibo import *
2165 1 1 2 3 5 8 13 21 34 55 89 144 233 377
2168 This imports all names except those beginning with an underscore
2172 \subsection{The Module Search Path
\label{searchPath
}}
2174 \indexiii{module
}{search
}{path
}
2175 When a module named
\module{spam
} is imported, the interpreter searches
2176 for a file named
\file{spam.py
} in the current directory,
2177 and then in the list of directories specified by
2178 the environment variable
\envvar{PYTHONPATH
}. This has the same syntax as
2179 the shell variable
\envvar{PATH
}, i.e., a list of
2180 directory names. When
\envvar{PYTHONPATH
} is not set, or when the file
2181 is not found there, the search continues in an installation-dependent
2182 default path; on
\UNIX{}, this is usually
\file{.:/usr/local/lib/python
}.
2184 Actually, modules are searched in the list of directories given by the
2185 variable
\code{sys.path
} which is initialized from the directory
2186 containing the input script (or the current directory),
2187 \envvar{PYTHONPATH
} and the installation-dependent default. This allows
2188 Python programs that know what they're doing to modify or replace the
2189 module search path. See the section on Standard Modules later.
2191 \subsection{``Compiled'' Python files
}
2193 As an important speed-up of the start-up time for short programs that
2194 use a lot of standard modules, if a file called
\file{spam.pyc
} exists
2195 in the directory where
\file{spam.py
} is found, this is assumed to
2196 contain an already-``byte-compiled'' version of the module
\module{spam
}.
2197 The modification time of the version of
\file{spam.py
} used to create
2198 \file{spam.pyc
} is recorded in
\file{spam.pyc
}, and the
2199 \file{.pyc
} file is ignored if these don't match.
2201 Normally, you don't need to do anything to create the
2202 \file{spam.pyc
} file. Whenever
\file{spam.py
} is successfully
2203 compiled, an attempt is made to write the compiled version to
2204 \file{spam.pyc
}. It is not an error if this attempt fails; if for any
2205 reason the file is not written completely, the resulting
2206 \file{spam.pyc
} file will be recognized as invalid and thus ignored
2207 later. The contents of the
\file{spam.pyc
} file are platform
2208 independent, so a Python module directory can be shared by machines of
2209 different architectures.
2211 Some tips for experts:
2216 When the Python interpreter is invoked with the
\programopt{-O
} flag,
2217 optimized code is generated and stored in
\file{.pyo
} files.
2218 The optimizer currently doesn't help much; it only removes
2219 \keyword{assert
} statements and
\code{SET_LINENO
} instructions.
2220 When
\programopt{-O
} is used,
\emph{all
} bytecode is optimized;
2221 \code{.pyc
} files are ignored and
\code{.py
} files are compiled to
2225 Passing two
\programopt{-O
} flags to the Python interpreter
2226 (
\programopt{-OO
}) will cause the bytecode compiler to perform
2227 optimizations that could in some rare cases result in malfunctioning
2228 programs. Currently only
\code{__doc__
} strings are removed from the
2229 bytecode, resulting in more compact
\file{.pyo
} files. Since some
2230 programs may rely on having these available, you should only use this
2231 option if you know what you're doing.
2234 A program doesn't run any faster when it is read from a
\file{.pyc
} or
2235 \file{.pyo
} file than when it is read from a
\file{.py
} file; the only
2236 thing that's faster about
\file{.pyc
} or
\file{.pyo
} files is the
2237 speed with which they are loaded.
2240 When a script is run by giving its name on the command line, the
2241 bytecode for the script is never written to a
\file{.pyc
} or
2242 \file{.pyo
} file. Thus, the startup time of a script may be reduced
2243 by moving most of its code to a module and having a small bootstrap
2244 script that imports that module. It is also possible to name a
2245 \file{.pyc
} or
\file{.pyo
} file directly on the command line.
2248 It is possible to have a file called
\file{spam.pyc
} (or
2249 \file{spam.pyo
} when
\programopt{-O
} is used) without a file
2250 \file{spam.py
} for the same module. This can be used to distribute a
2251 library of Python code in a form that is moderately hard to reverse
2255 The module
\module{compileall
}\refstmodindex{compileall
} can create
2256 \file{.pyc
} files (or
\file{.pyo
} files when
\programopt{-O
} is used) for
2257 all modules in a directory.
2262 \section{Standard Modules
\label{standardModules
}}
2264 Python comes with a library of standard modules, described in a separate
2265 document, the
\citetitle[../lib/lib.html
]{Python Library Reference
}
2266 (``Library Reference'' hereafter). Some modules are built into the
2267 interpreter; these provide access to operations that are not part of
2268 the core of the language but are nevertheless built in, either for
2269 efficiency or to provide access to operating system primitives such as
2270 system calls. The set of such modules is a configuration option; e.g.,
2271 the
\module{amoeba
} module is only provided on systems that somehow
2272 support Amoeba primitives. One particular module deserves some
2273 attention:
\module{sys
}\refstmodindex{sys
}, which is built into every
2274 Python interpreter. The variables
\code{sys.ps1
} and
2275 \code{sys.ps2
} define the strings used as primary and secondary
2290 These two variables are only defined if the interpreter is in
2293 The variable
\code{sys.path
} is a list of strings that determine the
2294 interpreter's search path for modules. It is initialized to a default
2295 path taken from the environment variable
\envvar{PYTHONPATH
}, or from
2296 a built-in default if
\envvar{PYTHONPATH
} is not set. You can modify
2297 it using standard list operations, e.g.:
2301 >>> sys.path.append('/ufs/guido/lib/python')
2304 \section{The
\function{dir()
} Function
\label{dir
}}
2306 The built-in function
\function{dir()
} is used to find out which names
2307 a module defines. It returns a sorted list of strings:
2310 >>> import fibo, sys
2312 ['__name__', 'fib', 'fib2'
]
2314 ['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
2315 'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
2316 'stderr', 'stdin', 'stdout', 'version'
]
2319 Without arguments,
\function{dir()
} lists the names you have defined
2323 >>> a =
[1,
2,
3,
4,
5]
2324 >>> import fibo, sys
2327 ['__name__', 'a', 'fib', 'fibo', 'sys'
]
2330 Note that it lists all types of names: variables, modules, functions, etc.
2332 \function{dir()
} does not list the names of built-in functions and
2333 variables. If you want a list of those, they are defined in the
2334 standard module
\module{__builtin__
}\refbimodindex{__builtin__
}:
2337 >>> import __builtin__
2338 >>> dir(__builtin__)
2339 ['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
2340 'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2341 'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
2342 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
2343 'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
2344 'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
2345 'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
2346 'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
2347 'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange'
]
2351 \section{Packages
\label{packages
}}
2353 Packages are a way of structuring Python's module namespace
2354 by using ``dotted module names''. For example, the module name
2355 \module{A.B
} designates a submodule named
\samp{B
} in a package named
2356 \samp{A
}. Just like the use of modules saves the authors of different
2357 modules from having to worry about each other's global variable names,
2358 the use of dotted module names saves the authors of multi-module
2359 packages like NumPy or the Python Imaging Library from having to worry
2360 about each other's module names.
2362 Suppose you want to design a collection of modules (a ``package'') for
2363 the uniform handling of sound files and sound data. There are many
2364 different sound file formats (usually recognized by their extension,
2365 e.g.
\file{.wav
},
\file{.aiff
},
\file{.au
}), so you may need to create
2366 and maintain a growing collection of modules for the conversion
2367 between the various file formats. There are also many different
2368 operations you might want to perform on sound data (e.g. mixing,
2369 adding echo, applying an equalizer function, creating an artificial
2370 stereo effect), so in addition you will be writing a never-ending
2371 stream of modules to perform these operations. Here's a possible
2372 structure for your package (expressed in terms of a hierarchical
2376 Sound/ Top-level package
2377 __init__.py Initialize the sound package
2378 Formats/ Subpackage for file format conversions
2387 Effects/ Subpackage for sound effects
2393 Filters/ Subpackage for filters
2401 The
\file{__init__.py
} files are required to make Python treat the
2402 directories as containing packages; this is done to prevent
2403 directories with a common name, such as
\samp{string
}, from
2404 unintentionally hiding valid modules that occur later on the module
2405 search path. In the simplest case,
\file{__init__.py
} can just be an
2406 empty file, but it can also execute initialization code for the
2407 package or set the
\code{__all__
} variable, described later.
2409 Users of the package can import individual modules from the
2410 package, for example:
2413 import Sound.Effects.echo
2416 This loads the submodule
\module{Sound.Effects.echo
}. It must be referenced
2417 with its full name, e.g.
2420 Sound.Effects.echo.echofilter(input, output, delay=
0.7, atten=
4)
2423 An alternative way of importing the submodule is:
2426 from Sound.Effects import echo
2429 This also loads the submodule
\module{echo
}, and makes it available without
2430 its package prefix, so it can be used as follows:
2433 echo.echofilter(input, output, delay=
0.7, atten=
4)
2436 Yet another variation is to import the desired function or variable directly:
2439 from Sound.Effects.echo import echofilter
2442 Again, this loads the submodule
\module{echo
}, but this makes its function
2443 \function{echofilter()
} directly available:
2446 echofilter(input, output, delay=
0.7, atten=
4)
2449 Note that when using
\code{from
\var{package
} import
\var{item
}}, the
2450 item can be either a submodule (or subpackage) of the package, or some
2451 other name defined in the package, like a function, class or
2452 variable. The
\code{import
} statement first tests whether the item is
2453 defined in the package; if not, it assumes it is a module and attempts
2454 to load it. If it fails to find it, an
2455 \exception{ImportError
} exception is raised.
2457 Contrarily, when using syntax like
\code{import
2458 \var{item.subitem.subsubitem
}}, each item except for the last must be
2459 a package; the last item can be a module or a package but can't be a
2460 class or function or variable defined in the previous item.
2462 \subsection{Importing * From a Package
\label{pkg-import-star
}}
2463 %The \code{__all__} Attribute
2465 Now what happens when the user writes
\code{from Sound.Effects import
2466 *
}? Ideally, one would hope that this somehow goes out to the
2467 filesystem, finds which submodules are present in the package, and
2468 imports them all. Unfortunately, this operation does not work very
2469 well on Mac and Windows platforms, where the filesystem does not
2470 always have accurate information about the case of a filename! On
2471 these platforms, there is no guaranteed way to know whether a file
2472 \file{ECHO.PY
} should be imported as a module
\module{echo
},
2473 \module{Echo
} or
\module{ECHO
}. (For example, Windows
95 has the
2474 annoying practice of showing all file names with a capitalized first
2475 letter.) The DOS
8+
3 filename restriction adds another interesting
2476 problem for long module names.
2478 The only solution is for the package author to provide an explicit
2479 index of the package. The import statement uses the following
2480 convention: if a package's
\file{__init__.py
} code defines a list
2481 named
\code{__all__
}, it is taken to be the list of module names that
2482 should be imported when
\code{from
\var{package
} import *
} is
2483 encountered. It is up to the package author to keep this list
2484 up-to-date when a new version of the package is released. Package
2485 authors may also decide not to support it, if they don't see a use for
2486 importing * from their package. For example, the file
2487 \file{Sounds/Effects/__init__.py
} could contain the following code:
2490 __all__ =
["echo", "surround", "reverse"
]
2493 This would mean that
\code{from Sound.Effects import *
} would
2494 import the three named submodules of the
\module{Sound
} package.
2496 If
\code{__all__
} is not defined, the statement
\code{from Sound.Effects
2497 import *
} does
\emph{not
} import all submodules from the package
2498 \module{Sound.Effects
} into the current namespace; it only ensures that the
2499 package
\module{Sound.Effects
} has been imported (possibly running its
2500 initialization code,
\file{__init__.py
}) and then imports whatever names are
2501 defined in the package. This includes any names defined (and
2502 submodules explicitly loaded) by
\file{__init__.py
}. It also includes any
2503 submodules of the package that were explicitly loaded by previous
2504 import statements, e.g.
2507 import Sound.Effects.echo
2508 import Sound.Effects.surround
2509 from Sound.Effects import *
2512 In this example, the echo and surround modules are imported in the
2513 current namespace because they are defined in the
2514 \module{Sound.Effects
} package when the
\code{from...import
} statement
2515 is executed. (This also works when
\code{__all__
} is defined.)
2517 Note that in general the practicing of importing * from a module or
2518 package is frowned upon, since it often causes poorly readable code.
2519 However, it is okay to use it to save typing in interactive sessions,
2520 and certain modules are designed to export only names that follow
2523 Remember, there is nothing wrong with using
\code{from Package
2524 import specific_submodule
}! In fact, this is the
2525 recommended notation unless the importing module needs to use
2526 submodules with the same name from different packages.
2529 \subsection{Intra-package References
}
2531 The submodules often need to refer to each other. For example, the
2532 \module{surround
} module might use the
\module{echo
} module. In fact, such references
2533 are so common that the
\code{import
} statement first looks in the
2534 containing package before looking in the standard module search path.
2535 Thus, the surround module can simply use
\code{import echo
} or
2536 \code{from echo import echofilter
}. If the imported module is not
2537 found in the current package (the package of which the current module
2538 is a submodule), the
\code{import
} statement looks for a top-level module
2539 with the given name.
2541 When packages are structured into subpackages (as with the
2542 \module{Sound
} package in the example), there's no shortcut to refer
2543 to submodules of sibling packages - the full name of the subpackage
2544 must be used. For example, if the module
2545 \module{Sound.Filters.vocoder
} needs to use the
\module{echo
} module
2546 in the
\module{Sound.Effects
} package, it can use
\code{from
2547 Sound.Effects import echo
}.
2549 %(One could design a notation to refer to parent packages, similar to
2550 %the use of ".." to refer to the parent directory in Unix and Windows
2551 %filesystems. In fact, the \module{ni} module, which was the
2552 %ancestor of this package system, supported this using \code{__} for
2553 %the package containing the current module,
2554 %\code{__.__} for the parent package, and so on. This feature was dropped
2555 %because of its awkwardness; since most packages will have a relative
2556 %shallow substructure, this is no big loss.)
2560 \chapter{Input and Output
\label{io
}}
2562 There are several ways to present the output of a program; data can be
2563 printed in a human-readable form, or written to a file for future use.
2564 This chapter will discuss some of the possibilities.
2567 \section{Fancier Output Formatting
\label{formatting
}}
2569 So far we've encountered two ways of writing values:
\emph{expression
2570 statements
} and the
\keyword{print
} statement. (A third way is using
2571 the
\method{write()
} method of file objects; the standard output file
2572 can be referenced as
\code{sys.stdout
}. See the Library Reference for
2573 more information on this.)
2575 Often you'll want more control over the formatting of your output than
2576 simply printing space-separated values. There are two ways to format
2577 your output; the first way is to do all the string handling yourself;
2578 using string slicing and concatenation operations you can create any
2579 lay-out you can imagine. The standard module
2580 \module{string
}\refstmodindex{string
} contains some useful operations
2581 for padding strings to a given column width; these will be discussed
2582 shortly. The second way is to use the
\code{\%
} operator with a
2583 string as the left argument. The
\code{\%
} operator interprets the
2584 left argument as a C much like a
\cfunction{sprintf()
}-style format
2585 string to be applied to the right argument, and returns the string
2586 resulting from this formatting operation.
2588 One question remains, of course: how do you convert values to strings?
2589 Luckily, Python has a way to convert any value to a string: pass it to
2590 the
\function{repr()
} function, or just write the value between
2591 reverse quotes (
\code{``
}). Some examples:
2596 >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
2598 The value of x is
31.4, and y is
40000...
2599 >>> # Reverse quotes work on other types besides numbers:
2604 >>> # Converting a string adds string quotes and backslashes:
2605 ... hello = 'hello, world
\n'
2606 >>> hellos = `hello`
2609 >>> # The argument of reverse quotes may be a tuple:
2610 ... `x, y, ('spam', 'eggs')`
2611 "(
31.4,
40000, ('spam', 'eggs'))"
2614 Here are two ways to write a table of squares and cubes:
2618 >>> for x in range(
1,
11):
2619 ... print string.rjust(`x`,
2), string.rjust(`x*x`,
3),
2620 ... # Note trailing comma on previous line
2621 ... print string.rjust(`x*x*x`,
4)
2633 >>> for x in range(
1,
11):
2634 ... print '
%2d %3d %4d' % (x, x*x, x*x*x)
2648 (Note that one space between each column was added by the way
2649 \keyword{print
} works: it always adds spaces between its arguments.)
2651 This example demonstrates the function
\function{string.rjust()
},
2652 which right-justifies a string in a field of a given width by padding
2653 it with spaces on the left. There are similar functions
2654 \function{string.ljust()
} and
\function{string.center()
}. These
2655 functions do not write anything, they just return a new string. If
2656 the input string is too long, they don't truncate it, but return it
2657 unchanged; this will mess up your column lay-out but that's usually
2658 better than the alternative, which would be lying about a value. (If
2659 you really want truncation you can always add a slice operation, as in
2660 \samp{string.ljust(x,~n)
[0:n
]}.)
2662 There is another function,
\function{string.zfill()
}, which pads a
2663 numeric string on the left with zeros. It understands about plus and
2668 >>> string.zfill('
12',
5)
2670 >>> string.zfill('-
3.14',
7)
2672 >>> string.zfill('
3.14159265359',
5)
2676 Using the
\code{\%
} operator looks like this:
2680 >>> print 'The value of PI is approximately
%5.3f.' % math.pi
2681 The value of PI is approximately
3.142.
2684 If there is more than one format in the string you pass a tuple as
2688 >>> table =
{'Sjoerd':
4127, 'Jack':
4098, 'Dcab':
7678}
2689 >>> for name, phone in table.items():
2690 ... print '
%-10s ==> %10d' % (name, phone)
2697 Most formats work exactly as in C and require that you pass the proper
2698 type; however, if you don't you get an exception, not a core dump.
2699 The
\code{\%s
} format is more relaxed: if the corresponding argument is
2700 not a string object, it is converted to string using the
2701 \function{str()
} built-in function. Using
\code{*
} to pass the width
2702 or precision in as a separate (integer) argument is supported. The
2703 C formats
\code{\%n
} and
\code{\%p
} are not supported.
2705 If you have a really long format string that you don't want to split
2706 up, it would be nice if you could reference the variables to be
2707 formatted by name instead of by position. This can be done by using
2708 an extension of C formats using the form
\code{\%(name)format
}, e.g.
2711 >>> table =
{'Sjoerd':
4127, 'Jack':
4098, 'Dcab':
8637678}
2712 >>> print 'Jack:
%(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2713 Jack:
4098; Sjoerd:
4127; Dcab:
8637678
2716 This is particularly useful in combination with the new built-in
2717 \function{vars()
} function, which returns a dictionary containing all
2720 \section{Reading and Writing Files
\label{files
}}
2723 \function{open()
}\bifuncindex{open
} returns a file
2724 object
\obindex{file
}, and is most commonly used with two arguments:
2725 \samp{open(
\var{filename
},
\var{mode
})
}.
2728 >>> f=open('/tmp/workfile', 'w')
2730 <open file '/tmp/workfile', mode 'w' at
80a0960>
2733 The first argument is a string containing the filename. The second
2734 argument is another string containing a few characters describing the
2735 way in which the file will be used.
\var{mode
} can be
\code{'r'
} when
2736 the file will only be read,
\code{'w'
} for only writing (an existing
2737 file with the same name will be erased), and
\code{'a'
} opens the file
2738 for appending; any data written to the file is automatically added to
2739 the end.
\code{'r+'
} opens the file for both reading and writing.
2740 The
\var{mode
} argument is optional;
\code{'r'
} will be assumed if
2743 On Windows and the Macintosh,
\code{'b'
} appended to the
2744 mode opens the file in binary mode, so there are also modes like
2745 \code{'rb'
},
\code{'wb'
}, and
\code{'r+b'
}. Windows makes a
2746 distinction between text and binary files; the end-of-line characters
2747 in text files are automatically altered slightly when data is read or
2748 written. This behind-the-scenes modification to file data is fine for
2749 \ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2750 \file{.EXE
} files. Be very careful to use binary mode when reading and
2751 writing such files. (Note that the precise semantics of text mode on
2752 the Macintosh depends on the underlying C library being used.)
2754 \subsection{Methods of File Objects
\label{fileMethods
}}
2756 The rest of the examples in this section will assume that a file
2757 object called
\code{f
} has already been created.
2759 To read a file's contents, call
\code{f.read(
\var{size
})
}, which reads
2760 some quantity of data and returns it as a string.
\var{size
} is an
2761 optional numeric argument. When
\var{size
} is omitted or negative,
2762 the entire contents of the file will be read and returned; it's your
2763 problem if the file is twice as large as your machine's memory.
2764 Otherwise, at most
\var{size
} bytes are read and returned. If the end
2765 of the file has been reached,
\code{f.read()
} will return an empty
2766 string (
\code {""
}).
2769 'This is the entire file.
\012'
2774 \code{f.readline()
} reads a single line from the file; a newline
2775 character (
\code{\e n
}) is left at the end of the string, and is only
2776 omitted on the last line of the file if the file doesn't end in a
2777 newline. This makes the return value unambiguous; if
2778 \code{f.readline()
} returns an empty string, the end of the file has
2779 been reached, while a blank line is represented by
\code{'
\e n'
}, a
2780 string containing only a single newline.
2784 'This is the first line of the file.
\012'
2786 'Second line of the file
\012'
2791 \code{f.readlines()
} returns a list containing all the lines of data
2792 in the file. If given an optional parameter
\var{sizehint
}, it reads
2793 that many bytes from the file and enough more to complete a line, and
2794 returns the lines from that. This is often used to allow efficient
2795 reading of a large file by lines, but without having to load the
2796 entire file in memory. Only complete lines will be returned.
2800 ['This is the first line of the file.
\012', 'Second line of the file
\012'
]
2803 \code{f.write(
\var{string
})
} writes the contents of
\var{string
} to
2804 the file, returning
\code{None
}.
2807 >>> f.write('This is a test
\n')
2810 \code{f.tell()
} returns an integer giving the file object's current
2811 position in the file, measured in bytes from the beginning of the
2812 file. To change the file object's position, use
2813 \samp{f.seek(
\var{offset
},
\var{from_what
})
}. The position is
2814 computed from adding
\var{offset
} to a reference point; the reference
2815 point is selected by the
\var{from_what
} argument. A
2816 \var{from_what
} value of
0 measures from the beginning of the file,
1
2817 uses the current file position, and
2 uses the end of the file as the
2818 reference point.
\var{from_what
} can be omitted and defaults to
0,
2819 using the beginning of the file as the reference point.
2822 >>> f=open('/tmp/workfile', 'r+')
2823 >>> f.write('
0123456789abcdef')
2824 >>> f.seek(
5) # Go to the
5th byte in the file
2827 >>> f.seek(-
3,
2) # Go to the
3rd byte before the end
2832 When you're done with a file, call
\code{f.close()
} to close it and
2833 free up any system resources taken up by the open file. After calling
2834 \code{f.close()
}, attempts to use the file object will automatically fail.
2839 Traceback (innermost last):
2840 File "<stdin>", line
1, in ?
2841 ValueError: I/O operation on closed file
2844 File objects have some additional methods, such as
2845 \method{isatty()
} and
\method{truncate()
} which are less frequently
2846 used; consult the Library Reference for a complete guide to file
2849 \subsection{The
\module{pickle
} Module
\label{pickle
}}
2850 \refstmodindex{pickle
}
2852 Strings can easily be written to and read from a file. Numbers take a
2853 bit more effort, since the
\method{read()
} method only returns
2854 strings, which will have to be passed to a function like
2855 \function{string.atoi()
}, which takes a string like
\code{'
123'
} and
2856 returns its numeric value
123. However, when you want to save more
2857 complex data types like lists, dictionaries, or class instances,
2858 things get a lot more complicated.
2860 Rather than have users be constantly writing and debugging code to
2861 save complicated data types, Python provides a standard module called
2862 \module{pickle
}. This is an amazing module that can take almost
2863 any Python object (even some forms of Python code!), and convert it to
2864 a string representation; this process is called
\dfn{pickling
}.
2865 Reconstructing the object from the string representation is called
2866 \dfn{unpickling
}. Between pickling and unpickling, the string
2867 representing the object may have been stored in a file or data, or
2868 sent over a network connection to some distant machine.
2870 If you have an object
\code{x
}, and a file object
\code{f
} that's been
2871 opened for writing, the simplest way to pickle the object takes only
2878 To unpickle the object again, if
\code{f
} is a file object which has
2879 been opened for reading:
2885 (There are other variants of this, used when pickling many objects or
2886 when you don't want to write the pickled data to a file; consult the
2887 complete documentation for
\module{pickle
} in the Library Reference.)
2889 \module{pickle
} is the standard way to make Python objects which can
2890 be stored and reused by other programs or by a future invocation of
2891 the same program; the technical term for this is a
2892 \dfn{persistent
} object. Because
\module{pickle
} is so widely used,
2893 many authors who write Python extensions take care to ensure that new
2894 data types such as matrices can be properly pickled and unpickled.
2898 \chapter{Errors and Exceptions
\label{errors
}}
2900 Until now error messages haven't been more than mentioned, but if you
2901 have tried out the examples you have probably seen some. There are
2902 (at least) two distinguishable kinds of errors:
2903 \emph{syntax errors
} and
\emph{exceptions
}.
2905 \section{Syntax Errors
\label{syntaxErrors
}}
2907 Syntax errors, also known as parsing errors, are perhaps the most common
2908 kind of complaint you get while you are still learning Python:
2911 >>> while
1 print 'Hello world'
2912 File "<stdin>", line
1
2913 while
1 print 'Hello world'
2915 SyntaxError: invalid syntax
2918 The parser repeats the offending line and displays a little `arrow'
2919 pointing at the earliest point in the line where the error was
2920 detected. The error is caused by (or at least detected at) the token
2921 \emph{preceding
} the arrow: in the example, the error is detected at
2922 the keyword
\keyword{print
}, since a colon (
\character{:
}) is missing
2923 before it. File name and line number are printed so you know where to
2924 look in case the input came from a script.
2926 \section{Exceptions
\label{exceptions
}}
2928 Even if a statement or expression is syntactically correct, it may
2929 cause an error when an attempt is made to execute it.
2930 Errors detected during execution are called
\emph{exceptions
} and are
2931 not unconditionally fatal: you will soon learn how to handle them in
2932 Python programs. Most exceptions are not handled by programs,
2933 however, and result in error messages as shown here:
2937 Traceback (innermost last):
2938 File "<stdin>", line
1
2939 ZeroDivisionError: integer division or modulo
2941 Traceback (innermost last):
2942 File "<stdin>", line
1
2945 Traceback (innermost last):
2946 File "<stdin>", line
1
2947 TypeError: illegal argument type for built-in operation
2950 The last line of the error message indicates what happened.
2951 Exceptions come in different types, and the type is printed as part of
2952 the message: the types in the example are
2953 \exception{ZeroDivisionError
},
\exception{NameError
} and
2954 \exception{TypeError
}.
2955 The string printed as the exception type is the name of the built-in
2956 name for the exception that occurred. This is true for all built-in
2957 exceptions, but need not be true for user-defined exceptions (although
2958 it is a useful convention).
2959 Standard exception names are built-in identifiers (not reserved
2962 The rest of the line is a detail whose interpretation depends on the
2963 exception type; its meaning is dependent on the exception type.
2965 The preceding part of the error message shows the context where the
2966 exception happened, in the form of a stack backtrace.
2967 In general it contains a stack backtrace listing source lines; however,
2968 it will not display lines read from standard input.
2970 The
\emph{Python Library Reference
} lists the built-in exceptions and
2974 \section{Handling Exceptions
\label{handling
}}
2976 It is possible to write programs that handle selected exceptions.
2977 Look at the following example, which asks the user for input until a
2978 valid integer has been entered, but allows the user to interrupt the
2979 program (using
\kbd{Control-C
} or whatever the operating system
2980 supports); note that a user-generated interruption is signalled by
2981 raising the
\exception{KeyboardInterrupt
} exception.
2986 ... x = int(raw_input("Please enter a number: "))
2988 ... except ValueError:
2989 ... print "Oops! That was no valid number. Try again..."
2993 The
\keyword{try
} statement works as follows.
2997 First, the
\emph{try clause
} (the statement(s) between the
2998 \keyword{try
} and
\keyword{except
} keywords) is executed.
3001 If no exception occurs, the
\emph{except\ clause
} is skipped and
3002 execution of the
\keyword{try
} statement is finished.
3005 If an exception occurs during execution of the try clause, the rest of
3006 the clause is skipped. Then if its type matches the exception named
3007 after the
\keyword{except
} keyword, the rest of the try clause is
3008 skipped, the except clause is executed, and then execution continues
3009 after the
\keyword{try
} statement.
3012 If an exception occurs which does not match the exception named in the
3013 except clause, it is passed on to outer
\keyword{try
} statements; if
3014 no handler is found, it is an
\emph{unhandled exception
} and execution
3015 stops with a message as shown above.
3019 A
\keyword{try
} statement may have more than one except clause, to
3020 specify handlers for different exceptions. At most one handler will
3021 be executed. Handlers only handle exceptions that occur in the
3022 corresponding try clause, not in other handlers of the same
3023 \keyword{try
} statement. An except clause may name multiple exceptions
3024 as a parenthesized list, e.g.:
3027 ... except (RuntimeError, TypeError, NameError):
3031 The last except clause may omit the exception name(s), to serve as a
3032 wildcard. Use this with extreme caution, since it is easy to mask a
3033 real programming error in this way! It can also be used to print an
3034 error message and then re-raise the exception (allowing a caller to
3035 handle the exception as well):
3041 f = open('myfile.txt')
3043 i = int(string.strip(s))
3044 except IOError, (errno, strerror):
3045 print "I/O error(
%s): %s" % (errno, strerror)
3047 print "Could not convert data to an integer."
3049 print "Unexpected error:", sys.exc_info()
[0]
3053 The
\keyword{try
} \ldots\
\keyword{except
} statement has an optional
3054 \emph{else clause
}, which, when present, must follow all except
3055 clauses. It is useful for code that must be executed if the try
3056 clause does not raise an exception. For example:
3059 for arg in sys.argv
[1:
]:
3063 print 'cannot open', arg
3065 print arg, 'has', len(f.readlines()), 'lines'
3069 The use of the
\keyword{else
} clause is better than adding additional
3070 code to the
\keyword{try
} clause because it avoids accidentally
3071 catching an exception that wasn't raised by the code being protected
3072 by the
\keyword{try
} \ldots\
\keyword{except
} statement.
3075 When an exception occurs, it may have an associated value, also known as
3076 the exception's
\emph{argument
}.
3077 The presence and type of the argument depend on the exception type.
3078 For exception types which have an argument, the except clause may
3079 specify a variable after the exception name (or list) to receive the
3080 argument's value, as follows:
3085 ... except NameError, x:
3086 ... print 'name', x, 'undefined'
3091 If an exception has an argument, it is printed as the last part
3092 (`detail') of the message for unhandled exceptions.
3094 Exception handlers don't just handle exceptions if they occur
3095 immediately in the try clause, but also if they occur inside functions
3096 that are called (even indirectly) in the try clause.
3100 >>> def this_fails():
3105 ... except ZeroDivisionError, detail:
3106 ... print 'Handling run-time error:', detail
3108 Handling run-time error: integer division or modulo
3112 \section{Raising Exceptions
\label{raising
}}
3114 The
\keyword{raise
} statement allows the programmer to force a
3115 specified exception to occur.
3119 >>> raise NameError, 'HiThere'
3120 Traceback (innermost last):
3121 File "<stdin>", line
1
3125 The first argument to
\keyword{raise
} names the exception to be
3126 raised. The optional second argument specifies the exception's
3130 \section{User-defined Exceptions
\label{userExceptions
}}
3132 Programs may name their own exceptions by assigning a string to a
3133 variable or creating a new exception class. For example:
3137 ... def __init__(self, value):
3138 ... self.value = value
3139 ... def __str__(self):
3140 ... return `self.value`
3143 ... raise MyError(
2*
2)
3144 ... except MyError, e:
3145 ... print 'My exception occurred, value:', e.value
3147 My exception occurred, value:
4
3148 >>> raise MyError,
1
3149 Traceback (innermost last):
3150 File "<stdin>", line
1
3154 Many standard modules use this to
report errors that may occur in
3155 functions they define.
3157 More information on classes is presented in chapter
\ref{classes
},
3161 \section{Defining Clean-up Actions
\label{cleanup
}}
3163 The
\keyword{try
} statement has another optional clause which is
3164 intended to define clean-up actions that must be executed under all
3165 circumstances. For example:
3169 ... raise KeyboardInterrupt
3171 ... print 'Goodbye, world!'
3174 Traceback (innermost last):
3175 File "<stdin>", line
2
3179 A
\emph{finally clause
} is executed whether or not an exception has
3180 occurred in the try clause. When an exception has occurred, it is
3181 re-raised after the finally clause is executed. The finally clause is
3182 also executed ``on the way out'' when the
\keyword{try
} statement is
3183 left via a
\keyword{break
} or
\keyword{return
} statement.
3185 A
\keyword{try
} statement must either have one or more except clauses
3186 or one finally clause, but not both.
3188 \chapter{Classes
\label{classes
}}
3190 Python's class mechanism adds classes to the language with a minimum
3191 of new syntax and semantics. It is a mixture of the class mechanisms
3192 found in
\Cpp{} and Modula-
3. As is true for modules, classes in Python
3193 do not put an absolute barrier between definition and user, but rather
3194 rely on the politeness of the user not to ``break into the
3195 definition.'' The most important features of classes are retained
3196 with full power, however: the class inheritance mechanism allows
3197 multiple base classes, a derived class can override any methods of its
3198 base class or classes, a method can call the method of a base class with the
3199 same name. Objects can contain an arbitrary amount of private data.
3201 In
\Cpp{} terminology, all class members (including the data members) are
3202 \emph{public
}, and all member functions are
\emph{virtual
}. There are
3203 no special constructors or destructors. As in Modula-
3, there are no
3204 shorthands for referencing the object's members from its methods: the
3205 method function is declared with an explicit first argument
3206 representing the object, which is provided implicitly by the call. As
3207 in Smalltalk, classes themselves are objects, albeit in the wider
3208 sense of the word: in Python, all data types are objects. This
3209 provides semantics for importing and renaming. But, just like in
3210 \Cpp{} or Modula-
3, built-in types cannot be used as base classes for
3211 extension by the user. Also, like in
\Cpp{} but unlike in Modula-
3, most
3212 built-in operators with special syntax (arithmetic operators,
3213 subscripting etc.) can be redefined for class instances.
3215 \section{A Word About Terminology
\label{terminology
}}
3217 Lacking universally accepted terminology to talk about classes, I will
3218 make occasional use of Smalltalk and
\Cpp{} terms. (I would use Modula-
3
3219 terms, since its object-oriented semantics are closer to those of
3220 Python than
\Cpp{}, but I expect that few readers have heard of it.)
3222 I also have to warn you that there's a terminological pitfall for
3223 object-oriented readers: the word ``object'' in Python does not
3224 necessarily mean a class instance. Like
\Cpp{} and Modula-
3, and
3225 unlike Smalltalk, not all types in Python are classes: the basic
3226 built-in types like integers and lists are not, and even somewhat more
3227 exotic types like files aren't. However,
\emph{all
} Python types
3228 share a little bit of common semantics that is best described by using
3231 Objects have individuality, and multiple names (in multiple scopes)
3232 can be bound to the same object. This is known as aliasing in other
3233 languages. This is usually not appreciated on a first glance at
3234 Python, and can be safely ignored when dealing with immutable basic
3235 types (numbers, strings, tuples). However, aliasing has an
3236 (intended!) effect on the semantics of Python code involving mutable
3237 objects such as lists, dictionaries, and most types representing
3238 entities outside the program (files, windows, etc.). This is usually
3239 used to the benefit of the program, since aliases behave like pointers
3240 in some respects. For example, passing an object is cheap since only
3241 a pointer is passed by the implementation; and if a function modifies
3242 an object passed as an argument, the caller will see the change --- this
3243 obviates the need for two different argument passing mechanisms as in
3247 \section{Python Scopes and Name Spaces
\label{scopes
}}
3249 Before introducing classes, I first have to tell you something about
3250 Python's scope rules. Class definitions play some neat tricks with
3251 namespaces, and you need to know how scopes and namespaces work to
3252 fully understand what's going on. Incidentally, knowledge about this
3253 subject is useful for any advanced Python programmer.
3255 Let's begin with some definitions.
3257 A
\emph{namespace
} is a mapping from names to objects. Most
3258 namespaces are currently implemented as Python dictionaries, but
3259 that's normally not noticeable in any way (except for performance),
3260 and it may change in the future. Examples of namespaces are: the set
3261 of built-in names (functions such as
\function{abs()
}, and built-in
3262 exception names); the global names in a module; and the local names in
3263 a function invocation. In a sense the set of attributes of an object
3264 also form a namespace. The important thing to know about namespaces
3265 is that there is absolutely no relation between names in different
3266 namespaces; for instance, two different modules may both define a
3267 function ``maximize'' without confusion --- users of the modules must
3268 prefix it with the module name.
3270 By the way, I use the word
\emph{attribute
} for any name following a
3271 dot --- for example, in the expression
\code{z.real
},
\code{real
} is
3272 an attribute of the object
\code{z
}. Strictly speaking, references to
3273 names in modules are attribute references: in the expression
3274 \code{modname.funcname
},
\code{modname
} is a module object and
3275 \code{funcname
} is an attribute of it. In this case there happens to
3276 be a straightforward mapping between the module's attributes and the
3277 global names defined in the module: they share the same namespace!
3279 Except for one thing. Module objects have a secret read-only
3280 attribute called
\member{__dict__
} which returns the dictionary
3281 used to implement the module's namespace; the name
3282 \member{__dict__
} is an attribute but not a global name.
3283 Obviously, using this violates the abstraction of namespace
3284 implementation, and should be restricted to things like
3285 post-mortem debuggers.
3288 Attributes may be read-only or writable. In the latter case,
3289 assignment to attributes is possible. Module attributes are writable:
3290 you can write
\samp{modname.the_answer =
42}. Writable attributes may
3291 also be deleted with the
\keyword{del
} statement, e.g.
3292 \samp{del modname.the_answer
}.
3294 Name spaces are created at different moments and have different
3295 lifetimes. The namespace containing the built-in names is created
3296 when the Python interpreter starts up, and is never deleted. The
3297 global namespace for a module is created when the module definition
3298 is read in; normally, module namespaces also last until the
3299 interpreter quits. The statements executed by the top-level
3300 invocation of the interpreter, either read from a script file or
3301 interactively, are considered part of a module called
3302 \module{__main__
}, so they have their own global namespace. (The
3303 built-in names actually also live in a module; this is called
3304 \module{__builtin__
}.)
3306 The local namespace for a function is created when the function is
3307 called, and deleted when the function returns or raises an exception
3308 that is not handled within the function. (Actually, forgetting would
3309 be a better way to describe what actually happens.) Of course,
3310 recursive invocations each have their own local namespace.
3312 A
\emph{scope
} is a textual region of a Python program where a
3313 namespace is directly accessible. ``Directly accessible'' here means
3314 that an unqualified reference to a name attempts to find the name in
3317 Although scopes are determined statically, they are used dynamically.
3318 At any time during execution, exactly three nested scopes are in use
3319 (i.e., exactly three namespaces are directly accessible): the
3320 innermost scope, which is searched first, contains the local names,
3321 the middle scope, searched next, contains the current module's global
3322 names, and the outermost scope (searched last) is the namespace
3323 containing built-in names.
3325 Usually, the local scope references the local names of the (textually)
3326 current function. Outside of functions, the local scope references
3327 the same namespace as the global scope: the module's namespace.
3328 Class definitions place yet another namespace in the local scope.
3330 It is important to realize that scopes are determined textually: the
3331 global scope of a function defined in a module is that module's
3332 namespace, no matter from where or by what alias the function is
3333 called. On the other hand, the actual search for names is done
3334 dynamically, at run time --- however, the language definition is
3335 evolving towards static name resolution, at ``compile'' time, so don't
3336 rely on dynamic name resolution! (In fact, local variables are
3337 already determined statically.)
3339 A special quirk of Python is that assignments always go into the
3340 innermost scope. Assignments do not copy data --- they just
3341 bind names to objects. The same is true for deletions: the statement
3342 \samp{del x
} removes the binding of
\code{x
} from the namespace
3343 referenced by the local scope. In fact, all operations that introduce
3344 new names use the local scope: in particular, import statements and
3345 function definitions bind the module or function name in the local
3346 scope. (The
\keyword{global
} statement can be used to indicate that
3347 particular variables live in the global scope.)
3350 \section{A First Look at Classes
\label{firstClasses
}}
3352 Classes introduce a little bit of new syntax, three new object types,
3353 and some new semantics.
3356 \subsection{Class Definition Syntax
\label{classDefinition
}}
3358 The simplest form of class definition looks like this:
3369 Class definitions, like function definitions
3370 (
\keyword{def
} statements) must be executed before they have any
3371 effect. (You could conceivably place a class definition in a branch
3372 of an
\keyword{if
} statement, or inside a function.)
3374 In practice, the statements inside a class definition will usually be
3375 function definitions, but other statements are allowed, and sometimes
3376 useful --- we'll come back to this later. The function definitions
3377 inside a class normally have a peculiar form of argument list,
3378 dictated by the calling conventions for methods --- again, this is
3381 When a class definition is entered, a new namespace is created, and
3382 used as the local scope --- thus, all assignments to local variables
3383 go into this new namespace. In particular, function definitions bind
3384 the name of the new function here.
3386 When a class definition is left normally (via the end), a
\emph{class
3387 object
} is created. This is basically a wrapper around the contents
3388 of the namespace created by the class definition; we'll learn more
3389 about class objects in the next section. The original local scope
3390 (the one in effect just before the class definitions was entered) is
3391 reinstated, and the class object is bound here to the class name given
3392 in the class definition header (
\class{ClassName
} in the example).
3395 \subsection{Class Objects
\label{classObjects
}}
3397 Class objects support two kinds of operations: attribute references
3400 \emph{Attribute references
} use the standard syntax used for all
3401 attribute references in Python:
\code{obj.name
}. Valid attribute
3402 names are all the names that were in the class's namespace when the
3403 class object was created. So, if the class definition looked like
3408 "A simple example class"
3411 return 'hello world'
3414 then
\code{MyClass.i
} and
\code{MyClass.f
} are valid attribute
3415 references, returning an integer and a method object, respectively.
3416 Class attributes can also be assigned to, so you can change the value
3417 of
\code{MyClass.i
} by assignment.
\member{__doc__
} is also a valid
3418 attribute, returning the docstring belonging to the class:
\code{"A
3419 simple example class"
}).
3421 Class
\emph{instantiation
} uses function notation. Just pretend that
3422 the class object is a parameterless function that returns a new
3423 instance of the class. For example (assuming the above class):
3429 creates a new
\emph{instance
} of the class and assigns this object to
3430 the local variable
\code{x
}.
3432 The instantiation operation (``calling'' a class object) creates an
3433 empty object. Many classes like to create objects in a known initial
3434 state. Therefore a class may define a special method named
3435 \method{__init__()
}, like this:
3442 When a class defines an
\method{__init__()
} method, class
3443 instantiation automatically invokes
\method{__init__()
} for the
3444 newly-created class instance. So in this example, a new, initialized
3445 instance can be obtained by:
3451 Of course, the
\method{__init__()
} method may have arguments for
3452 greater flexibility. In that case, arguments given to the class
3453 instantiation operator are passed on to
\method{__init__()
}. For
3458 ... def __init__(self, realpart, imagpart):
3459 ... self.r = realpart
3460 ... self.i = imagpart
3462 >>> x = Complex(
3.0,-
4.5)
3468 \subsection{Instance Objects
\label{instanceObjects
}}
3470 Now what can we do with instance objects? The only operations
3471 understood by instance objects are attribute references. There are
3472 two kinds of valid attribute names.
3474 The first I'll call
\emph{data attributes
}. These correspond to
3475 ``instance variables'' in Smalltalk, and to ``data members'' in
3476 \Cpp{}. Data attributes need not be declared; like local variables,
3477 they spring into existence when they are first assigned to. For
3478 example, if
\code{x
} is the instance of
\class{MyClass
} created above,
3479 the following piece of code will print the value
\code{16}, without
3484 while x.counter <
10:
3485 x.counter = x.counter *
2
3490 The second kind of attribute references understood by instance objects
3491 are
\emph{methods
}. A method is a function that ``belongs to'' an
3492 object. (In Python, the term method is not unique to class instances:
3493 other object types can have methods as well, e.g., list objects have
3494 methods called append, insert, remove, sort, and so on. However,
3495 below, we'll use the term method exclusively to mean methods of class
3496 instance objects, unless explicitly stated otherwise.)
3498 Valid method names of an instance object depend on its class. By
3499 definition, all attributes of a class that are (user-defined) function
3500 objects define corresponding methods of its instances. So in our
3501 example,
\code{x.f
} is a valid method reference, since
3502 \code{MyClass.f
} is a function, but
\code{x.i
} is not, since
3503 \code{MyClass.i
} is not. But
\code{x.f
} is not the same thing as
3504 \code{MyClass.f
} --- it is a
\obindex{method
}\emph{method object
}, not
3508 \subsection{Method Objects
\label{methodObjects
}}
3510 Usually, a method is called immediately, e.g.:
3516 In our example, this will return the string
\code{'hello world'
}.
3517 However, it is not necessary to call a method right away:
3518 \code{x.f
} is a method object, and can be stored away and called at a
3519 later time. For example:
3527 will continue to print
\samp{hello world
} until the end of time.
3529 What exactly happens when a method is called? You may have noticed
3530 that
\code{x.f()
} was called without an argument above, even though
3531 the function definition for
\method{f
} specified an argument. What
3532 happened to the argument? Surely Python raises an exception when a
3533 function that requires an argument is called without any --- even if
3534 the argument isn't actually used...
3536 Actually, you may have guessed the answer: the special thing about
3537 methods is that the object is passed as the first argument of the
3538 function. In our example, the call
\code{x.f()
} is exactly equivalent
3539 to
\code{MyClass.f(x)
}. In general, calling a method with a list of
3540 \var{n
} arguments is equivalent to calling the corresponding function
3541 with an argument list that is created by inserting the method's object
3542 before the first argument.
3544 If you still don't understand how methods work, a look at the
3545 implementation can perhaps clarify matters. When an instance
3546 attribute is referenced that isn't a data attribute, its class is
3547 searched. If the name denotes a valid class attribute that is a
3548 function object, a method object is created by packing (pointers to)
3549 the instance object and the function object just found together in an
3550 abstract object: this is the method object. When the method object is
3551 called with an argument list, it is unpacked again, a new argument
3552 list is constructed from the instance object and the original argument
3553 list, and the function object is called with this new argument list.
3556 \section{Random Remarks
\label{remarks
}}
3558 [These should perhaps be placed more carefully...
]
3561 Data attributes override method attributes with the same name; to
3562 avoid accidental name conflicts, which may cause hard-to-find bugs in
3563 large programs, it is wise to use some kind of convention that
3564 minimizes the chance of conflicts, e.g., capitalize method names,
3565 prefix data attribute names with a small unique string (perhaps just
3566 an underscore), or use verbs for methods and nouns for data attributes.
3569 Data attributes may be referenced by methods as well as by ordinary
3570 users (``clients'') of an object. In other words, classes are not
3571 usable to implement pure abstract data types. In fact, nothing in
3572 Python makes it possible to enforce data hiding --- it is all based
3573 upon convention. (On the other hand, the Python implementation,
3574 written in C, can completely hide implementation details and control
3575 access to an object if necessary; this can be used by extensions to
3576 Python written in C.)
3579 Clients should use data attributes with care --- clients may mess up
3580 invariants maintained by the methods by stamping on their data
3581 attributes. Note that clients may add data attributes of their own to
3582 an instance object without affecting the validity of the methods, as
3583 long as name conflicts are avoided --- again, a naming convention can
3584 save a lot of headaches here.
3587 There is no shorthand for referencing data attributes (or other
3588 methods!) from within methods. I find that this actually increases
3589 the readability of methods: there is no chance of confusing local
3590 variables and instance variables when glancing through a method.
3593 Conventionally, the first argument of methods is often called
3594 \code{self
}. This is nothing more than a convention: the name
3595 \code{self
} has absolutely no special meaning to Python. (Note,
3596 however, that by not following the convention your code may be less
3597 readable by other Python programmers, and it is also conceivable that
3598 a
\emph{class browser
} program be written which relies upon such a
3602 Any function object that is a class attribute defines a method for
3603 instances of that class. It is not necessary that the function
3604 definition is textually enclosed in the class definition: assigning a
3605 function object to a local variable in the class is also ok. For
3609 # Function defined outside the class
3616 return 'hello world'
3620 Now
\code{f
},
\code{g
} and
\code{h
} are all attributes of class
3621 \class{C
} that refer to function objects, and consequently they are all
3622 methods of instances of
\class{C
} ---
\code{h
} being exactly equivalent
3623 to
\code{g
}. Note that this practice usually only serves to confuse
3624 the reader of a program.
3627 Methods may call other methods by using method attributes of the
3628 \code{self
} argument, e.g.:
3636 def addtwice(self, x):
3641 Methods may reference global names in the same way as ordinary
3642 functions. The global scope associated with a method is the module
3643 containing the class definition. (The class itself is never used as a
3644 global scope!) While one rarely encounters a good reason for using
3645 global data in a method, there are many legitimate uses of the global
3646 scope: for one thing, functions and modules imported into the global
3647 scope can be used by methods, as well as functions and classes defined
3648 in it. Usually, the class containing the method is itself defined in
3649 this global scope, and in the next section we'll find some good
3650 reasons why a method would want to reference its own class!
3653 \section{Inheritance
\label{inheritance
}}
3655 Of course, a language feature would not be worthy of the name ``class''
3656 without supporting inheritance. The syntax for a derived class
3657 definition looks as follows:
3660 class DerivedClassName(BaseClassName):
3668 The name
\class{BaseClassName
} must be defined in a scope containing
3669 the derived class definition. Instead of a base class name, an
3670 expression is also allowed. This is useful when the base class is
3671 defined in another module, e.g.,
3674 class DerivedClassName(modname.BaseClassName):
3677 Execution of a derived class definition proceeds the same as for a
3678 base class. When the class object is constructed, the base class is
3679 remembered. This is used for resolving attribute references: if a
3680 requested attribute is not found in the class, it is searched in the
3681 base class. This rule is applied recursively if the base class itself
3682 is derived from some other class.
3684 There's nothing special about instantiation of derived classes:
3685 \code{DerivedClassName()
} creates a new instance of the class. Method
3686 references are resolved as follows: the corresponding class attribute
3687 is searched, descending down the chain of base classes if necessary,
3688 and the method reference is valid if this yields a function object.
3690 Derived classes may override methods of their base classes. Because
3691 methods have no special privileges when calling other methods of the
3692 same object, a method of a base class that calls another method
3693 defined in the same base class, may in fact end up calling a method of
3694 a derived class that overrides it. (For
\Cpp{} programmers: all methods
3695 in Python are effectively
\keyword{virtual
}.)
3697 An overriding method in a derived class may in fact want to extend
3698 rather than simply replace the base class method of the same name.
3699 There is a simple way to call the base class method directly: just
3700 call
\samp{BaseClassName.methodname(self, arguments)
}. This is
3701 occasionally useful to clients as well. (Note that this only works if
3702 the base class is defined or imported directly in the global scope.)
3705 \subsection{Multiple Inheritance
\label{multiple
}}
3707 Python supports a limited form of multiple inheritance as well. A
3708 class definition with multiple base classes looks as follows:
3711 class DerivedClassName(Base1, Base2, Base3):
3719 The only rule necessary to explain the semantics is the resolution
3720 rule used for class attribute references. This is depth-first,
3721 left-to-right. Thus, if an attribute is not found in
3722 \class{DerivedClassName
}, it is searched in
\class{Base1
}, then
3723 (recursively) in the base classes of
\class{Base1
}, and only if it is
3724 not found there, it is searched in
\class{Base2
}, and so on.
3726 (To some people breadth first --- searching
\class{Base2
} and
3727 \class{Base3
} before the base classes of
\class{Base1
} --- looks more
3728 natural. However, this would require you to know whether a particular
3729 attribute of
\class{Base1
} is actually defined in
\class{Base1
} or in
3730 one of its base classes before you can figure out the consequences of
3731 a name conflict with an attribute of
\class{Base2
}. The depth-first
3732 rule makes no differences between direct and inherited attributes of
3735 It is clear that indiscriminate use of multiple inheritance is a
3736 maintenance nightmare, given the reliance in Python on conventions to
3737 avoid accidental name conflicts. A well-known problem with multiple
3738 inheritance is a class derived from two classes that happen to have a
3739 common base class. While it is easy enough to figure out what happens
3740 in this case (the instance will have a single copy of ``instance
3741 variables'' or data attributes used by the common base class), it is
3742 not clear that these semantics are in any way useful.
3745 \section{Private Variables
\label{private
}}
3747 There is limited support for class-private
3748 identifiers. Any identifier of the form
\code{__spam
} (at least two
3749 leading underscores, at most one trailing underscore) is now textually
3750 replaced with
\code{_classname__spam
}, where
\code{classname
} is the
3751 current class name with leading underscore(s) stripped. This mangling
3752 is done without regard of the syntactic position of the identifier, so
3753 it can be used to define class-private instance and class variables,
3754 methods, as well as globals, and even to store instance variables
3755 private to this class on instances of
\emph{other
} classes. Truncation
3756 may occur when the mangled name would be longer than
255 characters.
3757 Outside classes, or when the class name consists of only underscores,
3760 Name mangling is intended to give classes an easy way to define
3761 ``private'' instance variables and methods, without having to worry
3762 about instance variables defined by derived classes, or mucking with
3763 instance variables by code outside the class. Note that the mangling
3764 rules are designed mostly to avoid accidents; it still is possible for
3765 a determined soul to access or modify a variable that is considered
3766 private. This can even be useful, e.g. for the debugger, and that's
3767 one reason why this loophole is not closed. (Buglet: derivation of a
3768 class with the same name as the base class makes use of private
3769 variables of the base class possible.)
3771 Notice that code passed to
\code{exec
},
\code{eval()
} or
3772 \code{evalfile()
} does not consider the classname of the invoking
3773 class to be the current class; this is similar to the effect of the
3774 \code{global
} statement, the effect of which is likewise restricted to
3775 code that is byte-compiled together. The same restriction applies to
3776 \code{getattr()
},
\code{setattr()
} and
\code{delattr()
}, as well as
3777 when referencing
\code{__dict__
} directly.
3779 Here's an example of a class that implements its own
3780 \method{__getattr__()
} and
\method{__setattr__()
} methods and stores
3781 all attributes in a private variable, in a way that works in all
3782 versions of Python, including those available before this feature was
3786 class VirtualAttributes:
3788 __vdict_name = locals().keys()
[0]
3791 self.__dict__
[self.__vdict_name
] =
{}
3793 def __getattr__(self, name):
3794 return self.__vdict
[name
]
3796 def __setattr__(self, name, value):
3797 self.__vdict
[name
] = value
3801 \section{Odds and Ends
\label{odds
}}
3803 Sometimes it is useful to have a data type similar to the Pascal
3804 ``record'' or C ``struct'', bundling together a couple of named data
3805 items. An empty class definition will do nicely, e.g.:
3811 john = Employee() # Create an empty employee record
3813 # Fill the fields of the record
3814 john.name = 'John Doe'
3815 john.dept = 'computer lab'
3819 A piece of Python code that expects a particular abstract data type
3820 can often be passed a class that emulates the methods of that data
3821 type instead. For instance, if you have a function that formats some
3822 data from a file object, you can define a class with methods
3823 \method{read()
} and
\method{readline()
} that gets the data from a string
3824 buffer instead, and pass it as an argument.
% (Unfortunately, this
3825 %technique has its limitations: a class can't define operations that
3826 %are accessed by special syntax such as sequence subscripting or
3827 %arithmetic operators, and assigning such a ``pseudo-file'' to
3828 %\code{sys.stdin} will not cause the interpreter to read further input
3832 Instance method objects have attributes, too:
\code{m.im_self
} is the
3833 object of which the method is an instance, and
\code{m.im_func
} is the
3834 function object corresponding to the method.
3836 \subsection{Exceptions Can Be Classes
\label{exceptionClasses
}}
3838 User-defined exceptions are no longer limited to being string objects
3839 --- they can be identified by classes as well. Using this mechanism it
3840 is possible to create extensible hierarchies of exceptions.
3842 There are two new valid (semantic) forms for the raise statement:
3845 raise Class, instance
3850 In the first form,
\code{instance
} must be an instance of
3851 \class{Class
} or of a class derived from it. The second form is a
3855 raise instance.__class__, instance
3858 An except clause may list classes as well as string objects. A class
3859 in an except clause is compatible with an exception if it is the same
3860 class or a base class thereof (but not the other way around --- an
3861 except clause listing a derived class is not compatible with a base
3862 class). For example, the following code will print B, C, D in that
3884 Note that if the except clauses were reversed (with
3885 \samp{except B
} first), it would have printed B, B, B --- the first
3886 matching except clause is triggered.
3888 When an error message is printed for an unhandled exception which is a
3889 class, the class name is printed, then a colon and a space, and
3890 finally the instance converted to a string using the built-in function
3894 \chapter{What Now?
\label{whatNow
}}
3896 Hopefully reading this tutorial has reinforced your interest in using
3897 Python. Now what should you do?
3899 You should read, or at least page through, the Library Reference,
3900 which gives complete (though terse) reference material about types,
3901 functions, and modules that can save you a lot of time when writing
3902 Python programs. The standard Python distribution includes a
3903 \emph{lot
} of code in both C and Python; there are modules to read
3904 \UNIX{} mailboxes, retrieve documents via HTTP, generate random
3905 numbers, parse command-line options, write CGI programs, compress
3906 data, and a lot more; skimming through the Library Reference will give
3907 you an idea of what's available.
3909 The major Python Web site is
\url{http://www.python.org/
}; it contains
3910 code, documentation, and pointers to Python-related pages around the
3911 Web. This web site is mirrored in various places around the
3912 world, such as Europe, Japan, and Australia; a mirror may be faster
3913 than the main site, depending on your geographical location. A more
3914 informal site is
\url{http://starship.python.net/
}, which contains a
3915 bunch of Python-related personal home pages; many people have
3916 downloadable software there.
3918 For Python-related questions and problem reports, you can post to the
3919 newsgroup
\newsgroup{comp.lang.python
}, or send them to the mailing
3920 list at
\email{python-list@python.org
}. The newsgroup and mailing list
3921 are gatewayed, so messages posted to one will automatically be
3922 forwarded to the other. There are around
120 postings a day,
3923 % Postings figure based on average of last six months activity as
3924 % reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182
3925 % days = 116.9 msgs / day and steadily increasing.
3926 asking (and answering) questions, suggesting new features, and
3927 announcing new modules. Before posting, be sure to check the list of
3928 Frequently Asked Questions (also called the FAQ), at
3929 \url{http://www.python.org/doc/FAQ.html
}, or look for it in the
3930 \file{Misc/
} directory of the Python source distribution. Mailing
3931 list archives are available at
\url{http://www.python.org/pipermail/
}.
3932 The FAQ answers many of the questions that come up again and again,
3933 and may already contain the solution for your problem.
3938 \chapter{Interactive Input Editing and History Substitution
3939 \label{interacting
}}
3941 Some versions of the Python interpreter support editing of the current
3942 input line and history substitution, similar to facilities found in
3943 the Korn shell and the GNU Bash shell. This is implemented using the
3944 \emph{GNU Readline
} library, which supports Emacs-style and vi-style
3945 editing. This library has its own documentation which I won't
3946 duplicate here; however, the basics are easily explained. The
3947 interactive editing and history described here are optionally
3948 available in the
\UNIX{} and CygWin versions of the interpreter.
3950 This chapter does
\emph{not
} document the editing facilities of Mark
3951 Hammond's PythonWin package or the Tk-based environment, IDLE,
3952 distributed with Python. The command line history recall which
3953 operates within DOS boxes on NT and some other DOS and Windows flavors
3954 is yet another beast.
3956 \section{Line Editing
\label{lineEditing
}}
3958 If supported, input line editing is active whenever the interpreter
3959 prints a primary or secondary prompt. The current line can be edited
3960 using the conventional Emacs control characters. The most important
3961 of these are:
\kbd{C-A
} (Control-A) moves the cursor to the beginning
3962 of the line,
\kbd{C-E
} to the end,
\kbd{C-B
} moves it one position to
3963 the left,
\kbd{C-F
} to the right. Backspace erases the character to
3964 the left of the cursor,
\kbd{C-D
} the character to its right.
3965 \kbd{C-K
} kills (erases) the rest of the line to the right of the
3966 cursor,
\kbd{C-Y
} yanks back the last killed string.
3967 \kbd{C-underscore
} undoes the last change you made; it can be repeated
3968 for cumulative effect.
3970 \section{History Substitution
\label{history
}}
3972 History substitution works as follows. All non-empty input lines
3973 issued are saved in a history buffer, and when a new prompt is given
3974 you are positioned on a new line at the bottom of this buffer.
3975 \kbd{C-P
} moves one line up (back) in the history buffer,
3976 \kbd{C-N
} moves one down. Any line in the history buffer can be
3977 edited; an asterisk appears in front of the prompt to mark a line as
3978 modified. Pressing the
\kbd{Return
} key passes the current line to
3979 the interpreter.
\kbd{C-R
} starts an incremental reverse search;
3980 \kbd{C-S
} starts a forward search.
3982 \section{Key Bindings
\label{keyBindings
}}
3984 The key bindings and some other parameters of the Readline library can
3985 be customized by placing commands in an initialization file called
3986 \file{\~
{}/.inputrc
}. Key bindings have the form
3989 key-name: function-name
3995 "string": function-name
3998 and options can be set with
4001 set option-name value
4007 # I prefer vi-style editing:
4010 # Edit using a single line:
4011 set horizontal-scroll-mode On
4014 Meta-h: backward-kill-word
4015 "
\C-u": universal-argument
4016 "
\C-x
\C-r": re-read-init-file
4019 Note that the default binding for
\kbd{Tab
} in Python is to insert a
4020 \kbd{Tab
} character instead of Readline's default filename completion
4021 function. If you insist, you can override this by putting
4027 in your
\file{\~
{}/.inputrc
}. (Of course, this makes it harder to
4028 type indented continuation lines.)
4030 Automatic completion of variable and module names is optionally
4031 available. To enable it in the interpreter's interactive mode, add
4032 the following to your startup file:
\footnote{
4033 Python will execute the contents of a file identified by the
4034 \envvar{PYTHONSTARTUP
} environment variable when you start an
4035 interactive interpreter.
}
4036 \refstmodindex{rlcompleter
}\refbimodindex{readline
}
4039 import rlcompleter, readline
4040 readline.parse_and_bind('tab: complete')
4043 This binds the TAB key to the completion function, so hitting the TAB
4044 key twice suggests completions; it looks at Python statement names,
4045 the current local variables, and the available module names. For
4046 dotted expressions such as
\code{string.a
}, it will evaluate the the
4047 expression up to the final
\character{.
} and then suggest completions
4048 from the attributes of the resulting object. Note that this may
4049 execute application-defined code if an object with a
4050 \method{__getattr__()
} method is part of the expression.
4053 \section{Commentary
\label{commentary
}}
4055 This facility is an enormous step forward compared to earlier versions
4056 of the interpreter; however, some wishes are left: It would be nice if
4057 the proper indentation were suggested on continuation lines (the
4058 parser knows if an indent token is required next). The completion
4059 mechanism might use the interpreter's symbol table. A command to
4060 check (or even suggest) matching parentheses, quotes, etc., would also
4064 \chapter{History and License
}