blob: a6c2876637540dfcd0393d0c255fdf26b0941796 [file] [log] [blame]
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001\documentstyle[11pt,myformat]{report}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002
Guido van Rossum862c6f11992-01-29 14:47:05 +00003\title{\bf Python Reference Manual}
4
Guido van Rossumf2612d11991-11-21 13:53:03 +00005\author{
6 Guido van Rossum \\
7 Dept. CST, CWI, Kruislaan 413 \\
8 1098 SJ Amsterdam, The Netherlands \\
9 E-mail: {\tt guido@cwi.nl}
10}
11
12\begin{document}
13
14\pagenumbering{roman}
15
16\maketitle
17
18\begin{abstract}
19
20\noindent
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000021Python is a simple, yet powerful, interpreted programming language
22that bridges the gap between C and shell programming, and is thus
23ideally suited for ``throw-away programming'' and rapid prototyping.
24Its syntax is put together from constructs borrowed from a variety of
25other languages; most prominent are influences from ABC, C, Modula-3
26and Icon.
Guido van Rossumf2612d11991-11-21 13:53:03 +000027
28The Python interpreter is easily extended with new functions and data
29types implemented in C. Python is also suitable as an extension
30language for highly customizable C applications such as editors or
31window managers.
32
33Python is available for various operating systems, amongst which
34several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S.,
35and MS-DOS.
36
37This reference manual describes the syntax and ``core semantics'' of
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000038the language. It is terse, but attempts to be exact and complete.
39The semantics of non-essential built-in object types and of the
40built-in functions and modules are described in the {\em Python
41Library Reference}. For an informal introduction to the language, see
42the {\em Python Tutorial}.
Guido van Rossumf2612d11991-11-21 13:53:03 +000043
44\end{abstract}
45
46\pagebreak
47
Guido van Rossum670e5a01992-01-17 14:03:20 +000048{
49\parskip = 0mm
Guido van Rossumf2612d11991-11-21 13:53:03 +000050\tableofcontents
Guido van Rossum670e5a01992-01-17 14:03:20 +000051}
Guido van Rossumf2612d11991-11-21 13:53:03 +000052
53\pagebreak
54
55\pagenumbering{arabic}
56
57\chapter{Introduction}
58
59This reference manual describes the Python programming language.
60It is not intended as a tutorial.
61
Guido van Rossum743d1e71992-01-07 16:43:53 +000062While I am trying to be as precise as possible, I chose to use English
63rather than formal specifications for everything except syntax and
64lexical analysis. This should make the document better understandable
65to the average reader, but will leave room for ambiguities.
66Consequently, if you were coming from Mars and tried to re-implement
Guido van Rossum7b632a61992-01-16 17:49:21 +000067Python from this document alone, you might have to guess things and in
68fact you would be implementing quite a different language.
69On the other hand, if you are using
Guido van Rossum743d1e71992-01-07 16:43:53 +000070Python and wonder what the precise rules about a particular area of
Guido van Rossum7b632a61992-01-16 17:49:21 +000071the language are, you should definitely be able to find it here.
Guido van Rossum743d1e71992-01-07 16:43:53 +000072
73It is dangerous to add too many implementation details to a language
74reference document -- the implementation may change, and other
75implementations of the same language may work differently. On the
76other hand, there is currently only one Python implementation, and
Guido van Rossum7b632a61992-01-16 17:49:21 +000077its particular quirks are sometimes worth being mentioned, especially
78where the implementation imposes additional limitations.
Guido van Rossum743d1e71992-01-07 16:43:53 +000079
80Every Python implementation comes with a number of built-in and
81standard modules. These are not documented here, but in the separate
82{\em Python Library Reference} document. A few built-in modules are
83mentioned when they interact in a significant way with the language
84definition.
85
86\section{Notation}
87
88The descriptions of lexical analysis and syntax use a modified BNF
89grammar notation. This uses the following style of definition:
90
91\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000092name: lc_letter (lc_letter | "_")*
93lc_letter: "a"..."z"
Guido van Rossum743d1e71992-01-07 16:43:53 +000094\end{verbatim}
95
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000096The first line says that a \verb\name\ is an \verb\lc_letter\ followed by
97a sequence of zero or more \verb\lc_letter\s and underscores. An
98\verb\lc_letter\ in turn is any of the single characters `a' through `z'.
Guido van Rossum743d1e71992-01-07 16:43:53 +000099(This rule is actually adhered to for the names defined in syntax and
100grammar rules in this document.)
101
102Each rule begins with a name (which is the name defined by the rule)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000103and a colon. A vertical bar
Guido van Rossum7b632a61992-01-16 17:49:21 +0000104(\verb\|\) is used to separate alternatives; it is the least binding
105operator in this notation. A star (\verb\*\) means zero or more
106repetitions of the preceding item; likewise, a plus (\verb\+\) means
107one or more repetitions, and a question mark (\verb\?\) zero or one
108(in other words, the preceding item is optional). These three
109operators bind as tightly as possible; parentheses are used for
Guido van Rossum743d1e71992-01-07 16:43:53 +0000110grouping. Literal strings are enclosed in double quotes. White space
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000111is only meaningful to separate tokens. Rules are normally contained
112on a single line; rules with many alternatives may be formatted
113alternatively with each line after the first beginning with a
114vertical bar.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000115
116In lexical definitions (as the example above), two more conventions
117are used: Two literal characters separated by three dots mean a choice
118of any single character in the given (inclusive) range of ASCII
119characters. A phrase between angular brackets (\verb\<...>\) gives an
120informal description of the symbol defined; e.g., this could be used
121to describe the notion of `control character' if needed.
122
Guido van Rossum7b632a61992-01-16 17:49:21 +0000123Even though the notation used is almost the same, there is a big
Guido van Rossum743d1e71992-01-07 16:43:53 +0000124difference between the meaning of lexical and syntactic definitions:
125a lexical definition operates on the individual characters of the
126input source, while a syntax definition operates on the stream of
127tokens generated by the lexical analysis.
128
Guido van Rossumf2612d11991-11-21 13:53:03 +0000129\chapter{Lexical analysis}
130
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000131A Python program is read by a {\em parser}. Input to the parser is a
132stream of {\em tokens}, generated by the {\em lexical analyzer}. This
133chapter describes how the lexical analyzer breaks a file into tokens.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000134
135\section{Line structure}
136
Guido van Rossum7b632a61992-01-16 17:49:21 +0000137A Python program is divided in a number of logical lines. The end of
138a logical line is represented by the token NEWLINE. Statements cannot
139cross logical line boundaries except where NEWLINE is allowed by the
140syntax (e.g., between statements in compound statements).
Guido van Rossumf2612d11991-11-21 13:53:03 +0000141
142\subsection{Comments}
143
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000144A comment starts with a hash character (\verb\#\) that is not part of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000145a string literal, and ends at the end of the physical line. A comment
146always signifies the end of the logical line. Comments are ignored by
147the syntax.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000148
149\subsection{Line joining}
150
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000151Two or more physical lines may be joined into logical lines using
Guido van Rossum7b632a61992-01-16 17:49:21 +0000152backslash characters (\verb/\/), as follows: when a physical line ends
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000153in a backslash that is not part of a string literal or comment, it is
154joined with the following forming a single logical line, deleting the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000155backslash and the following end-of-line character. For example:
156%
157\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000158moth_names = ['Januari', 'Februari', 'Maart', \
159 'April', 'Mei', 'Juni', \
160 'Juli', 'Augustus', 'September', \
161 'Oktober', 'November', 'December']
Guido van Rossum670e5a01992-01-17 14:03:20 +0000162\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000163
164\subsection{Blank lines}
165
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000166A logical line that contains only spaces, tabs, and possibly a
167comment, is ignored (i.e., no NEWLINE token is generated), except that
168during interactive input of statements, an entirely blank logical line
169terminates a multi-line statement.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000170
171\subsection{Indentation}
172
Guido van Rossum7b632a61992-01-16 17:49:21 +0000173Leading whitespace (spaces and tabs) at the beginning of a logical
174line is used to compute the indentation level of the line, which in
175turn is used to determine the grouping of statements.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000176
Guido van Rossum7b632a61992-01-16 17:49:21 +0000177First, tabs are replaced (from left to right) by one to eight spaces
178such that the total number of characters up to there is a multiple of
179eight (this is intended to be the same rule as used by UNIX). The
180total number of spaces preceding the first non-blank character then
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000181determines the line's indentation. Indentation cannot be split over
182multiple physical lines using backslashes.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000183
184The indentation levels of consecutive lines are used to generate
185INDENT and DEDENT tokens, using a stack, as follows.
186
187Before the first line of the file is read, a single zero is pushed on
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000188the stack; this will never be popped off again. The numbers pushed on
189the stack will always be strictly increasing from bottom to top. At
190the beginning of each logical line, the line's indentation level is
191compared to the top of the stack. If it is equal, nothing happens.
192If it larger, it is pushed on the stack, and one INDENT token is
193generated. If it is smaller, it {\em must} be one of the numbers
194occurring on the stack; all numbers on the stack that are larger are
195popped off, and for each number popped off a DEDENT token is
196generated. At the end of the file, a DEDENT token is generated for
197each number remaining on the stack that is larger than zero.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000198
Guido van Rossum7b632a61992-01-16 17:49:21 +0000199Here is an example of a correctly (though confusingly) indented piece
200of Python code:
201
202\begin{verbatim}
203def perm(l):
Guido van Rossum670e5a01992-01-17 14:03:20 +0000204 # Compute the list of all permutations of l
205
Guido van Rossum7b632a61992-01-16 17:49:21 +0000206 if len(l) <= 1:
207 return [l]
208 r = []
209 for i in range(len(l)):
210 s = l[:i] + l[i+1:]
211 p = perm(s)
212 for x in p:
213 r.append(l[i:i+1] + x)
214 return r
215\end{verbatim}
216
217The following example shows various indentation errors:
218
219\begin{verbatim}
220 def perm(l): # error: first line indented
221 for i in range(len(l)): # error: not indented
222 s = l[:i] + l[i+1:]
223 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
224 for x in p:
225 r.append(l[i:i+1] + x)
226 return r # error: inconsistent indent
227\end{verbatim}
228
229(Actually, the first three errors are detected by the parser; only the
230last error is found by the lexical analyzer -- the indentation of
231\verb\return r\ does not match a level popped off the stack.)
232
Guido van Rossumf2612d11991-11-21 13:53:03 +0000233\section{Other tokens}
234
235Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
236exist: identifiers, keywords, literals, operators, and delimiters.
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000237Spaces and tabs are not tokens, but serve to delimit tokens. Where
238ambiguity exists, a token comprises the longest possible string that
239forms a legal token, when read from left to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000240
Guido van Rossumf2612d11991-11-21 13:53:03 +0000241\section{Identifiers}
242
243Identifiers are described by the following regular expressions:
244
245\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000246identifier: (letter|"_") (letter|digit|"_")*
Guido van Rossumf2612d11991-11-21 13:53:03 +0000247letter: lowercase | uppercase
Guido van Rossum743d1e71992-01-07 16:43:53 +0000248lowercase: "a"..."z"
249uppercase: "A"..."Z"
250digit: "0"..."9"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000251\end{verbatim}
252
Guido van Rossum670e5a01992-01-17 14:03:20 +0000253Identifiers are unlimited in length. Case is significant.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000254
Guido van Rossum670e5a01992-01-17 14:03:20 +0000255\subsection{Keywords}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000256
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000257The following identifiers are used as reserved words, or {\em
Guido van Rossum7b632a61992-01-16 17:49:21 +0000258keywords} of the language, and cannot be used as ordinary
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000259identifiers. They must be spelled exactly as written here:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000260
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000261\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000262and del for in print
263break elif from is raise
264class else global not return
265continue except if or try
266def finally import pass while
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000267\end{verbatim}
268
Guido van Rossum743d1e71992-01-07 16:43:53 +0000269% # This Python program sorts and formats the above table
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000270% import string
271% l = []
272% try:
273% while 1:
274% l = l + string.split(raw_input())
275% except EOFError:
276% pass
277% l.sort()
278% for i in range((len(l)+4)/5):
279% for j in range(i, len(l), 5):
280% print string.ljust(l[j], 10),
281% print
Guido van Rossumf2612d11991-11-21 13:53:03 +0000282
283\section{Literals}
284
285\subsection{String literals}
286
287String literals are described by the following regular expressions:
288
289\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000290stringliteral: "'" stringitem* "'"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000291stringitem: stringchar | escapeseq
Guido van Rossum743d1e71992-01-07 16:43:53 +0000292stringchar: <any ASCII character except newline or "\" or "'">
293escapeseq: "'" <any ASCII character except newline>
Guido van Rossumf2612d11991-11-21 13:53:03 +0000294\end{verbatim}
295
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000296String literals cannot span physical line boundaries. Escape
297sequences in strings are actually interpreted according to rules
298simular to those used by Standard C. The recognized escape sequences
299are:
300
301\begin{center}
302\begin{tabular}{|l|l|}
303\hline
304\verb/\\/ & Backslash (\verb/\/) \\
305\verb/\'/ & Single quote (\verb/'/) \\
306\verb/\a/ & ASCII Bell (BEL) \\
307\verb/\b/ & ASCII Backspace (BS) \\
Guido van Rossum7b632a61992-01-16 17:49:21 +0000308%\verb/\E/ & ASCII Escape (ESC) \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000309\verb/\f/ & ASCII Formfeed (FF) \\
310\verb/\n/ & ASCII Linefeed (LF) \\
311\verb/\r/ & ASCII Carriage Return (CR) \\
312\verb/\t/ & ASCII Horizontal Tab (TAB) \\
313\verb/\v/ & ASCII Vertical Tab (VT) \\
314\verb/\/{\em ooo} & ASCII character with octal value {\em ooo} \\
Guido van Rossum743d1e71992-01-07 16:43:53 +0000315\verb/\x/{em xx...} & ASCII character with hex value {\em xx...} \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000316\hline
317\end{tabular}
318\end{center}
319
Guido van Rossum7b632a61992-01-16 17:49:21 +0000320In strict compatibility with in Standard C, up to three octal digits are
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000321accepted, but an unlimited number of hex digits is taken to be part of
322the hex escape (and then the lower 8 bits of the resulting hex number
Guido van Rossum7b632a61992-01-16 17:49:21 +0000323are used in all current implementations...).
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000324
Guido van Rossum7b632a61992-01-16 17:49:21 +0000325All unrecognized escape sequences are left in the string unchanged,
326i.e., {\em the backslash is left in the string.} (This rule is
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000327useful when debugging: if an escape sequence is mistyped, the
Guido van Rossum743d1e71992-01-07 16:43:53 +0000328resulting output is more easily recognized as broken. It also helps a
329great deal for string literals used as regular expressions or
330otherwise passed to other modules that do their own escape handling --
331but you may end up quadrupling backslashes that must appear literally.)
Guido van Rossumf2612d11991-11-21 13:53:03 +0000332
333\subsection{Numeric literals}
334
Guido van Rossum670e5a01992-01-17 14:03:20 +0000335There are three types of numeric literals: plain integers, long
336integers, and floating point numbers.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000337
338Integers and long integers are described by the following regular expressions:
339
340\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000341longinteger: integer ("l"|"L")
Guido van Rossumf2612d11991-11-21 13:53:03 +0000342integer: decimalinteger | octinteger | hexinteger
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000343decimalinteger: nonzerodigit digit* | "0"
344octinteger: "0" octdigit+
345hexinteger: "0" ("x"|"X") hexdigit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000346
Guido van Rossum743d1e71992-01-07 16:43:53 +0000347nonzerodigit: "1"..."9"
348octdigit: "0"..."7"
349hexdigit: digit|"a"..."f"|"A"..."F"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000350\end{verbatim}
351
Guido van Rossum670e5a01992-01-17 14:03:20 +0000352Although both lower case `l'and upper case `L' are allowed as suffix
353for long integers, it is strongly recommended to always use `L', since
354the letter `l' looks too much like the digit `1'.
355
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000356Plain integer decimal literals must be at most $2^{31} - 1$ (i.e., the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000357largest positive integer, assuming 32-bit arithmetic); octal and
358hexadecimal literals may be as large as $2^{32} - 1$. There is no limit
359for long integer literals.
360
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000361Some examples of plain and long integer literals:
Guido van Rossum670e5a01992-01-17 14:03:20 +0000362
363\begin{verbatim}
3647 2147483647 0177 0x80000000
3653L 79228162514264337593543950336L 0377L 0100000000L
366\end{verbatim}
367
Guido van Rossumf2612d11991-11-21 13:53:03 +0000368Floating point numbers are described by the following regular expressions:
369
370\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000371floatnumber: pointfloat | exponentfloat
372pointfloat: [intpart] fraction | intpart "."
373exponentfloat: (intpart | pointfloat) exponent
Guido van Rossumf2612d11991-11-21 13:53:03 +0000374intpart: digit+
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000375fraction: "." digit+
376exponent: ("e"|"E") ["+"|"-"] digit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000377\end{verbatim}
378
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000379The allowed range of floating point literals is
380implementation-dependent.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000381
382Some examples of floating point literals:
Guido van Rossum7b632a61992-01-16 17:49:21 +0000383
384\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00003853.14 10. .001 1e100 3.14e-10
Guido van Rossum7b632a61992-01-16 17:49:21 +0000386\end{verbatim}
387
Guido van Rossum670e5a01992-01-17 14:03:20 +0000388Note that numeric literals do not include a sign; a phrase like
389\verb\-1\ is actually an expression composed of the operator
Guido van Rossum7b632a61992-01-16 17:49:21 +0000390\verb\-\ and the literal \verb\1\.
391
Guido van Rossumf2612d11991-11-21 13:53:03 +0000392\section{Operators}
393
394The following tokens are operators:
395
396\begin{verbatim}
397+ - * / %
398<< >> & | ^ ~
Guido van Rossum743d1e71992-01-07 16:43:53 +0000399< == > <= <> != >=
Guido van Rossumf2612d11991-11-21 13:53:03 +0000400\end{verbatim}
401
Guido van Rossum743d1e71992-01-07 16:43:53 +0000402The comparison operators \verb\<>\ and \verb\!=\ are alternate
403spellings of the same operator.
404
Guido van Rossumf2612d11991-11-21 13:53:03 +0000405\section{Delimiters}
406
Guido van Rossum743d1e71992-01-07 16:43:53 +0000407The following tokens serve as delimiters or otherwise have a special
408meaning:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000409
410\begin{verbatim}
411( ) [ ] { }
Guido van Rossum743d1e71992-01-07 16:43:53 +0000412; , : . ` =
Guido van Rossumf2612d11991-11-21 13:53:03 +0000413\end{verbatim}
414
Guido van Rossum7b632a61992-01-16 17:49:21 +0000415The following printing ASCII characters are not used in Python (except
416in string literals and in comments). Their occurrence is an
417unconditional error:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000418
419\begin{verbatim}
420! @ $ " ?
421\end{verbatim}
422
Guido van Rossum7b632a61992-01-16 17:49:21 +0000423They may be used by future versions of the language though!
424
Guido van Rossumf2612d11991-11-21 13:53:03 +0000425\chapter{Execution model}
426
Guido van Rossum743d1e71992-01-07 16:43:53 +0000427\section{Objects, values and types}
428
429I won't try to define rigorously here what an object is, but I'll give
430some properties of objects that are important to know about.
431
432Every object has an identity, a type and a value. An object's {\em
433identity} never changes once it has been created; think of it as the
434object's (permanent) address. An object's {\em type} determines the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000435operations that an object supports (e.g., does it have a length?) and
436also defines the ``meaning'' of the object's value. The type also
437never changes. The {\em value} of some objects can change; whether
438this is possible is a property of its type.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000439
440Objects are never explicitly destroyed; however, when they become
Guido van Rossum670e5a01992-01-17 14:03:20 +0000441unreachable they may be garbage-collected. An implementation is
442allowed to delay garbage collection or omit it altogether -- it is a
443matter of implementation quality how garbage collection is
444implemented, as long as no objects are collected that are still
445reachable. (Implementation note: the current implementation uses a
Guido van Rossum743d1e71992-01-07 16:43:53 +0000446reference-counting scheme which collects most objects as soon as they
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000447become unreachable, but never collects garbage containing circular
Guido van Rossum743d1e71992-01-07 16:43:53 +0000448references.)
449
Guido van Rossum670e5a01992-01-17 14:03:20 +0000450Note that the use of the implementation's tracing or debugging
451facilities may keep objects alive that would normally be collectable.
452
Guido van Rossum743d1e71992-01-07 16:43:53 +0000453(Some objects contain references to ``external'' resources such as
454open files. It is understood that these resources are freed when the
455object is garbage-collected, but since garbage collection is not
Guido van Rossum670e5a01992-01-17 14:03:20 +0000456guaranteed, such objects also provide an explicit way to release the
457external resource (e.g., a \verb\close\ method). Programs are strongly
Guido van Rossum743d1e71992-01-07 16:43:53 +0000458recommended to use this.)
459
460Some objects contain references to other objects. These references
461are part of the object's value; in most cases, when such a
462``container'' object is compared to another (of the same type), the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000463comparison applies to the {\em values} of the referenced objects (not
464their identities).
Guido van Rossum743d1e71992-01-07 16:43:53 +0000465
Guido van Rossum670e5a01992-01-17 14:03:20 +0000466Types affect almost all aspects of objects.
467Even object identity is affected in some sense: for immutable
Guido van Rossum743d1e71992-01-07 16:43:53 +0000468types, operations that compute new values may actually return a
Guido van Rossum670e5a01992-01-17 14:03:20 +0000469reference to any existing object with the same type and value, while
Guido van Rossum743d1e71992-01-07 16:43:53 +0000470for mutable objects this is not allowed. E.g., after
471
472\begin{verbatim}
473a = 1; b = 1; c = []; d = []
474\end{verbatim}
475
476\verb\a\ and \verb\b\ may or may not refer to the same object, but
477\verb\c\ and \verb\d\ are guaranteed to refer to two different, unique,
478newly created lists.
479
480\section{Execution frames, name spaces, and scopes}
481
Guido van Rossum670e5a01992-01-17 14:03:20 +0000482XXX code blocks, scopes, name spaces, name binding, exceptions
Guido van Rossumf2612d11991-11-21 13:53:03 +0000483
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000484\chapter{The standard type hierarchy}
485
Guido van Rossum862c6f11992-01-29 14:47:05 +0000486Below is a list of the types that are built into Python. Extension
487modules written in C can define additional types. Future versions of
488Python may add types to the type hierarchy (e.g., rational or complex
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000489numbers, lists of efficiently stored integers, etc.).
490
Guido van Rossum862c6f11992-01-29 14:47:05 +0000491Some type descriptions contain a paragraph listing `special
492attributes'. These are attributes that provide access to the
493implementation and are not intended for general use. Their definition
494may change in the future. There are also some `generic' special
495attributes, not listed with the individual objects: \verb\__methods__\
496is a list of the method names of a built-in object, if it has any;
497\verb\__members__\ is a list of the data attribute names of a built-in
498object, if it has any.
499
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000500\begin{description}
501
502\item[None]
503This type has a single value. There is a single object with this value.
504This object is accessed through the built-in name \verb\None\.
505It is returned from functions that don't explicitly return an object.
506
507\item[Numbers]
508These are created by numeric literals and returned as results
509by arithmetic operators and arithmetic built-in functions.
510Numeric objects are immutable; once created their value never changes.
511Python numbers are of course strongly related to mathematical numbers,
512but subject to the limitations of numerical representation in computers.
513
514Python distinguishes between integers and floating point numbers:
515
516\begin{description}
517\item[Integers]
518These represent elements from the mathematical set of whole numbers.
519
520There are two types of integers:
521
522\begin{description}
523
524\item[Plain integers]
525These represent numbers in the range $-2^{31}$ through $2^{31}-1$.
526(The range may be larger on machines with a larger natural word
527size, but not smaller.)
528When the result of an operation falls outside this range, the
529exception \verb\OverflowError\ is raised.
530For the purpose of shift and mask operations, integers are assumed to
531have a binary, 2's complement notation using 32 or more bits, and
532hiding no bits from the user (i.e., all $2^{32}$ different bit
533patterns correspond to different values).
534
535\item[Long integers]
536These represent numbers in an unlimited range, subject to avaiable
537(virtual) memory only. For the purpose of shift and mask operations,
538a binary representation is assumed, and negative numbers are
539represented in a variant of 2's complement which gives the illusion of
540an infinite string of sign bits extending to the left.
541
542\end{description} % Integers
543
544The rules for integer representation are intended to give the most
545meaningful interpretation of shift and mask operations involving
546negative integers and the least surprises when switching between the
547plain and long integer domains. For any operation except left shift,
548if it yields a result in the plain integer domain without causing
549overflow, it will yield the same result in the long integer domain or
550when using mixed operands.
551
552\item[Floating point numbers]
553These represent machine-level double precision floating point numbers.
554You are at the mercy of the underlying machine architecture and
555C implementation for the accepted range and handling of overflow.
556
557\end{description} % Numbers
558
559\item[Sequences]
560These represent finite ordered sets indexed by natural numbers.
561The built-in function \verb\len()\ returns the number of elements
562of a sequence. When this number is $n$, the index set contains
563the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence
564\verb\a\ is selected by \verb\a[i]\.
565
566Sequences also support slicing: \verb\a[i:j]\ selects all elements
567with index $k$ such that $i < k < j$. When used as an expression,
568a slice is a sequence of the same type -- this implies that the
569index set is renumbered so that it starts at 0 again.
570
571Sequences are distinguished according to their mutability:
572
573\begin{description}
574%
575\item[Immutable sequences]
576An object of an immutable sequence type cannot change once it is
577created. (If the object contains references to other objects,
578these other objects may be mutable and may be changed; however
579the collection of objects directly referenced by an immutable object
580cannot change.)
581
582The following types are immutable sequences:
583
584\begin{description}
585
586\item[Strings]
587The elements of a string are characters. There is no separate
588character type; a character is represented by a string of one element.
589Characters represent (at least) 8-bit bytes. The built-in
590functions \verb\chr()\ and \verb\ord()\ convert between characters
591and nonnegative integers representing the byte values.
592Bytes with the values 0-127 represent the corresponding ASCII values.
593
594(On systems whose native character set is not ASCII, strings may use
595EBCDIC in their internal representation, provided the functions
596\verb\chr()\ and \verb\ord()\ implement a mapping between ASCII and
597EBCDIC, and string comparisons preserve the ASCII order.
598Or perhaps someone can propose a better rule?)
599
600\item[Tuples]
601The elements of a tuple are arbitrary Python objects.
602Tuples of two or more elements are formed by comma-separated lists
603of expressions. A tuple of one element can be formed by affixing
604a comma to an expression (an expression by itself of course does
605not create a tuple). An empty tuple can be formed by enclosing
606`nothing' in parentheses.
607
608\end{description} % Immutable sequences
609
610\item[Mutable sequences]
611Mutable sequences can be changed after they are created.
612The subscript and slice notations can be used as the target
613of assignment and \verb\del\ (delete) statements.
614
615There is currently a single mutable sequence type:
616
617\begin{description}
618
619\item[Lists]
620The elements of a list are arbitrary Python objects.
621Lists are formed by placing a comma-separated list of expressions
622in square brackets. (Note that there are no special cases for lists
623of length 0 or 1.)
624
625\end{description} % Mutable sequences
626
627\end{description} % Sequences
628
629\item[Mapping types]
630These represent finite sets of objects indexed by arbitrary index sets.
631The subscript notation \verb\a[k]\ selects the element indexed
632by \verb\k\ from the mapping \verb\a\; this can be used in
633expressions and as the target of assignments or \verb\del\ statements.
634The built-in function \verb\len()\ returns the number of elements
635in a mapping.
636
637There is currently a single mapping type:
638
639\begin{description}
640
641\item[Dictionaries]
642These represent finite sets of objects indexed by strings.
643Dictionaries are created by the \verb\{...}\ notation (see section
644\ref{dict}). (Implementation note: the strings used for indexing must
645not contain null bytes.)
646
647\end{description} % Mapping types
648
649\item[Callable types]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000650These are the types to which the function call operation (written as
651\verb\function(argument, argument, ...)\) can be applied:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000652
653\begin{description}
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000654
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000655\item[User-defined functions]
Guido van Rossum862c6f11992-01-29 14:47:05 +0000656A user-defined function is created by a function definition (see
657section \ref{function}). It should be called with an argument list
658containing the same number of items as the function's formal parameter
659list.
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000660
661Special read-only attributes: \verb\func_code\ is the code object
662representing the compiled function body, and \verb\func_globals\ is (a
663reference to) the dictionary that holds the function's global
664variables -- it implements the global name space of the module in
665which the function was defined.
666
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000667\item[User-defined methods]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000668A user-defined method (a.k.a. {\tt object closure}) is a pair of a
669class instance object and a user-defined function. It should be
670called with an argument list containing one item less than the number
671of items in the function's formal parameter list. When called, the
672class instance becomes the first argument, and the call arguments are
673shifted one to the right.
674
675Special read-only attributes: \verb\im_self\ is the class instance
676object, \verb\im_func\ is the function object.
677
678\item[Built-in functions]
679A built-in function object is a wrapper around a C function. Examples
680of built-in functions are \verb\len\ and \verb\math.sin\. There
681are no special attributes. The number and type of the arguments are
682determined by the C function.
683
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000684\item[Built-in methods]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000685This is really a different disguise of a built-in function, this time
686containing an object passed to the C function as an implicit extra
687argument. An example of a built-in method is \verb\list.append\ if
688\verb\list\ is a list object.
689
690\item[Classes]
691Class objects are described below. When a class object is called as a
692parameterless function, a new class instance (also described below) is
693created and returned. The class's initialization function is not
694called -- this is the responsibility of the caller. It is illegal to
695call a class object with one or more arguments.
696
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000697\end{description}
698
699\item[Modules]
Guido van Rossum862c6f11992-01-29 14:47:05 +0000700Modules are imported by the \verb\import\ statement (see section
701\ref{import}). A module object is a container for a module's name
702space, which is a dictionary (the same dictionary as referenced by the
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000703\ver\func_globals\ attribute of functions defined in the module).
704Module attribute references are translated to lookups in this
705dictionary. A module object does not contain the code object used to
706initialize the module (since it isn't needed once the initialization
707is done).
708
Guido van Rossum862c6f11992-01-29 14:47:05 +0000709Attribute assignment update the module's name space dictionary.
710
711Special read-only attributes: \verb\__dict__\ yields the module's name
712space as a dictionary object; \verb\__name__\ yields the module's name.
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000713
714\item[Classes]
Guido van Rossum862c6f11992-01-29 14:47:05 +0000715Class objects are created by class definitions (see section
716\ref{class}). A class is a container for a dictionary containing the
717class's name space. Class attribute references are translated to
718lookups in this dictionary. When an attribute name is not found
719there, the attribute search continues in the base classes. The search
720is depth-first, left-to-right in the order of their occurrence in the
721base class list.
722
723Attribute assignments update the class's dictionary, never the
724dictionary of a base class.
725
726A class can be called as a parameterless function to yield a class
727instance (see above).
728
729Special read-only attributes: \verb\__dict__\ yields te dictionary
730containing the class's name space; \verb\__bases__\ yields a tuple
731(possibly empty or a singleton) containing the base classes, in the
732order of their occurrence in the base class list.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000733
734\item[Class instances]
Guido van Rossum862c6f11992-01-29 14:47:05 +0000735A class instance is created by calling a class object as a
736parameterless function. A class instance has a dictionary in which
737attribute references are searched. When an attribute is not found
738there, and the instance's class has an attribute by that name, and
739that class attribute is a user-defined function (and in no other
740cases), the instance attribute reference yields a user-defined method
741object (see above) constructed from the instance and the function.
742
743Attribute assignments update the instance's dictionary.
744
745Special read-only attributes: \verb\__dict__\ yields the attribute
746dictionary; \verb\__class__\ yields the instance's class.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000747
748\item[Files]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000749A file object represents an open file. (It is a wrapper around a C
750{\tt stdio} file pointer.) File objects are created by the
751\verb\open()\ built-in function, and also by \verb\posix.popen()\ and
752the \verb\makefile\ method of socket objects. \verb\sys.stdin\,
753\verb\sys.stdout\ and \verb\sys.stderr\ are file objects corresponding
754the the interpreter's standard input, output and error streams.
755See the Python Library Reference for methods of file objects and other
756details.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000757
758\item[Internal types]
759A few types used internally by the interpreter are exposed to the user.
760Their definition may change with future versions of the interpreter,
761but they are mentioned here for completeness.
762
763\begin{description}
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000764
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000765\item[Code objects]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000766Code objects represent executable code. The difference between a code
767object and a function object is that the function object contains an
768explicit reference to the function's context (the module in which it
769was defined) which a code object contains no context. There is no way
770to execute a bare code object.
771
772Special read-only attributes: \verb\co_code\ is a string representing
773the sequence of instructions; \verb\co_consts\ is a list of literals
774used by the code; \verb\co_names\ is a list of names (strings) used by
775the code; \verb\co_filename\ is the filename from which the code was
776compiled. (To find out the line numbers, you would have to decode the
777instructions; the standard library module \verb\dis\ contains an
778example of how to do this.)
779
780\item[Frame objects]
781Frame objects represent execution frames. They may occur in traceback
782objects (see below).
783
784Special read-only attributes: \verb\f_back\ is to the previous
785stack frame (towards the caller), or \verb\None\ if this is the bottom
786stack frame; \verb\f_code\ is the code object being executed in this
787frame; \verb\f_globals\ is the dictionary used to look up global
788variables; \verb\f_locals\ is used for local variables;
789\verb\f_lineno\ gives the line number and \verb\f_lasti\ gives the
790precise instruction (this is an index into the instruction string of
791the code object).
792
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000793\item[Traceback objects]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000794Traceback objects represent a stack trace of an exception. A
795traceback object is created when an exception occurs. When the search
796for an exception handler unwinds the execution stack, at each unwound
797level a traceback object is inserted in front of the current
798traceback. When an exception handler is entered, the stack trace is
799made available to the program as \verb\sys.exc_traceback\. When the
800program contains no suitable handler, the stack trace is written
801(nicely formatted) to the standard error stream; if the interpreter is
802interactive, it is made available to the user as
803\verb\sys.last_traceback\.
804
805Special read-only attributes: \verb\tb_next\ is the next level in the
806stack trace (towards the frame where the exception occurred), or
807\verb\None\ if there is no next level; \verb\tb_frame\ points to the
808execution frame of the current level; \verb\tb_lineno\ gives the line
809number where the exception occurred; \verb\tb_lasti\ indicates the
810precise instruction. The line number and last instruction in the
811traceback may differ from the line number of its frame object if the
812exception occurred in a \verb\try\ statement with no matching
813\verb\except\ clause or with a \verb\finally\ clause.
814
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000815\end{description} % Internal types
816
817\end{description} % Types
818
Guido van Rossumf2612d11991-11-21 13:53:03 +0000819\chapter{Expressions and conditions}
820
Guido van Rossum743d1e71992-01-07 16:43:53 +0000821From now on, extended BNF notation will be used to describe syntax,
822not lexical analysis.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000823
824This chapter explains the meaning of the elements of expressions and
825conditions. Conditions are a superset of expressions, and a condition
Guido van Rossum670e5a01992-01-17 14:03:20 +0000826may be used wherever an expression is required by enclosing it in
827parentheses. The only places where expressions are used in the syntax
828instead of conditions is in expression statements and on the
829right-hand side of assignments; this catches some nasty bugs like
830accedentally writing \verb\x == 1\ instead of \verb\x = 1\.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000831
Guido van Rossum670e5a01992-01-17 14:03:20 +0000832The comma has several roles in Python's syntax. It is usually an
Guido van Rossum743d1e71992-01-07 16:43:53 +0000833operator with a lower precedence than all others, but occasionally
Guido van Rossum670e5a01992-01-17 14:03:20 +0000834serves other purposes as well; e.g., it separates function arguments,
835is used in list and dictionary constructors, and has special semantics
836in \verb\print\ statements.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000837
838When (one alternative of) a syntax rule has the form
839
840\begin{verbatim}
841name: othername
842\end{verbatim}
843
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000844and no semantics are given, the semantics of this form of \verb\name\
845are the same as for \verb\othername\.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000846
847\section{Arithmetic conversions}
848
849When a description of an arithmetic operator below uses the phrase
850``the numeric arguments are converted to a common type'',
851this both means that if either argument is not a number, a
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000852\verb\TypeError\ exception is raised, and that otherwise
Guido van Rossumf2612d11991-11-21 13:53:03 +0000853the following conversions are applied:
854
855\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000856\item first, if either argument is a floating point number,
Guido van Rossumf2612d11991-11-21 13:53:03 +0000857 the other is converted to floating point;
858\item else, if either argument is a long integer,
859 the other is converted to long integer;
Guido van Rossum670e5a01992-01-17 14:03:20 +0000860\item otherwise, both must be plain integers and no conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +0000861 is necessary.
862\end{itemize}
863
Guido van Rossumf2612d11991-11-21 13:53:03 +0000864\section{Atoms}
865
Guido van Rossum670e5a01992-01-17 14:03:20 +0000866Atoms are the most basic elements of expressions. Forms enclosed in
867reverse quotes or in parentheses, brackets or braces are also
868categorized syntactically as atoms. The syntax for atoms is:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000869
870\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000871atom: identifier | literal | enclosure
872enclosure: parenth_form | list_display | dict_display | string_conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +0000873\end{verbatim}
874
875\subsection{Identifiers (Names)}
876
877An identifier occurring as an atom is a reference to a local, global
Guido van Rossum670e5a01992-01-17 14:03:20 +0000878or built-in name binding. If a name can be assigned to anywhere in a
879code block, and is not mentioned in a \verb\global\ statement in that
880code block, it refers to a local name throughout that code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000881Otherwise, it refers to a global name if one exists, else to a
882built-in name.
883
Guido van Rossum670e5a01992-01-17 14:03:20 +0000884When the name is bound to an object, evaluation of the atom yields
885that object. When a name is not bound, an attempt to evaluate it
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000886raises a \verb\NameError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000887
888\subsection{Literals}
889
Guido van Rossum670e5a01992-01-17 14:03:20 +0000890Python knows string and numeric literals:
891
892\begin{verbatim}
893literal: stringliteral | integer | longinteger | floatnumber
894\end{verbatim}
895
Guido van Rossumf2612d11991-11-21 13:53:03 +0000896Evaluation of a literal yields an object of the given type
897(string, integer, long integer, floating point number)
898with the given value.
899The value may be approximated in the case of floating point literals.
900
Guido van Rossum670e5a01992-01-17 14:03:20 +0000901All literals correspond to immutable data types, and hence the
902object's identity is less important than its value. Multiple
903evaluations of literals with the same value (either the same
904occurrence in the program text or a different occurrence) may obtain
905the same object or a different object with the same value.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000906
907(In the original implementation, all literals in the same code block
908with the same type and value yield the same object.)
909
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000910\subsection{Parenthesized forms}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000911
Guido van Rossum670e5a01992-01-17 14:03:20 +0000912A parenthesized form is an optional condition list enclosed in
913parentheses:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000914
Guido van Rossum670e5a01992-01-17 14:03:20 +0000915\begin{verbatim}
916parenth_form: "(" [condition_list] ")"
917\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000918
Guido van Rossum670e5a01992-01-17 14:03:20 +0000919A parenthesized condition list yields whatever that condition list
920yields.
921
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000922An empty pair of parentheses yields an empty tuple object. Since
923tuples are immutable, the rules for literals apply here.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000924
925(Note that tuples are not formed by the parentheses, but rather by use
926of the comma operator. The exception is the empty tuple, for which
927parentheses {\em are} required -- allowing unparenthesized ``nothing''
928in expressions would causes ambiguities and allow common typos to
929pass uncaught.)
Guido van Rossumf2612d11991-11-21 13:53:03 +0000930
931\subsection{List displays}
932
Guido van Rossum670e5a01992-01-17 14:03:20 +0000933A list display is a possibly empty series of conditions enclosed in
934square brackets:
935
936\begin{verbatim}
937list_display: "[" [condition_list] "]"
938\end{verbatim}
939
Guido van Rossumf2612d11991-11-21 13:53:03 +0000940A list display yields a new list object.
941
942If it has no condition list, the list object has no items.
943Otherwise, the elements of the condition list are evaluated
944from left to right and inserted in the list object in that order.
945
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000946\subsection{Dictionary displays} \label{dict}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000947
Guido van Rossum670e5a01992-01-17 14:03:20 +0000948A dictionary display is a possibly empty series of key/datum pairs
949enclosed in curly braces:
950
951\begin{verbatim}
952dict_display: "{" [key_datum_list] "}"
953key_datum_list: [key_datum ("," key_datum)* [","]
954key_datum: condition ":" condition
955\end{verbatim}
956
Guido van Rossumf2612d11991-11-21 13:53:03 +0000957A dictionary display yields a new dictionary object.
958
Guido van Rossum670e5a01992-01-17 14:03:20 +0000959The key/datum pairs are evaluated from left to right to define the
960entries of the dictionary: each key object is used as a key into the
961dictionary to store the corresponding datum.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000962
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000963Keys must be strings, otherwise a \verb\TypeError\ exception is raised.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000964Clashes between duplicate keys are not detected; the last datum
965(textually rightmost in the display) stored for a given key value
966prevails.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000967
968\subsection{String conversions}
969
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000970A string conversion is a condition list enclosed in reverse (or
Guido van Rossum670e5a01992-01-17 14:03:20 +0000971backward) quotes:
972
973\begin{verbatim}
974string_conversion: "`" condition_list "`"
975\end{verbatim}
976
Guido van Rossumf2612d11991-11-21 13:53:03 +0000977A string conversion evaluates the contained condition list and converts the
978resulting object into a string according to rules specific to its type.
979
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000980If the object is a string, a number, \verb\None\, or a tuple, list or
Guido van Rossum670e5a01992-01-17 14:03:20 +0000981dictionary containing only objects whose type is one of these, the
982resulting string is a valid Python expression which can be passed to
983the built-in function \verb\eval()\ to yield an expression with the
Guido van Rossumf2612d11991-11-21 13:53:03 +0000984same value (or an approximation, if floating point numbers are
985involved).
986
987(In particular, converting a string adds quotes around it and converts
988``funny'' characters to escape sequences that are safe to print.)
989
Guido van Rossum670e5a01992-01-17 14:03:20 +0000990It is illegal to attempt to convert recursive objects (e.g., lists or
991dictionaries that contain a reference to themselves, directly or
992indirectly.)
Guido van Rossumf2612d11991-11-21 13:53:03 +0000993
994\section{Primaries}
995
996Primaries represent the most tightly bound operations of the language.
997Their syntax is:
998
999\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001000primary: atom | attributeref | subscription | slicing | call
Guido van Rossumf2612d11991-11-21 13:53:03 +00001001\end{verbatim}
1002
1003\subsection{Attribute references}
1004
Guido van Rossum670e5a01992-01-17 14:03:20 +00001005An attribute reference is a primary followed by a period and a name:
1006
1007\begin{verbatim}
1008attributeref: primary "." identifier
1009\end{verbatim}
1010
1011The primary must evaluate to an object of a type that supports
1012attribute references, e.g., a module or a list. This object is then
1013asked to produce the attribute whose name is the identifier. If this
1014attribute is not available, the exception \verb\AttributeError\ is
1015raised. Otherwise, the type and value of the object produced is
1016determined by the object. Multiple evaluations of the same attribute
1017reference may yield different objects.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001018
1019\subsection{Subscriptions}
1020
Guido van Rossum670e5a01992-01-17 14:03:20 +00001021A subscription selects an item of a sequence or mapping object:
1022
1023\begin{verbatim}
1024subscription: primary "[" condition "]"
1025\end{verbatim}
1026
1027The primary must evaluate to an object of a sequence or mapping type.
1028
1029If it is a mapping, the condition must evaluate to an object whose
1030value is one of the keys of the mapping, and the subscription selects
1031the value in the mapping that corresponds to that key.
1032
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001033If it is a sequence, the condition must evaluate to a plain integer.
1034If this value is negative, the length of the sequence is added to it
1035(so that, e.g., \verb\x[-1]\ selects the last item of \verb\x\.)
1036The resulting value must be a nonnegative integer smaller than the
1037number of items in the sequence, and the subscription selects the item
1038whose index is that value (counting from zero).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001039
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001040A string's items are characters. A character is not a separate data
Guido van Rossum670e5a01992-01-17 14:03:20 +00001041type but a string of exactly one character.
1042
Guido van Rossumf2612d11991-11-21 13:53:03 +00001043\subsection{Slicings}
1044
Guido van Rossum670e5a01992-01-17 14:03:20 +00001045A slicing selects a range of items in a sequence object:
1046
1047\begin{verbatim}
1048slicing: primary "[" [condition] ":" [condition] "]"
1049\end{verbatim}
1050
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001051The primary must evaluate to a sequence object. The lower and upper
1052bound expressions, if present, must evaluate to plain integers;
1053defaults are zero and the sequence's length, respectively. If either
1054bound is negative, the sequence's length is added to it. The slicing
1055now selects all items with index $k$ such that $i <= k < j$ where $i$
1056and $j$ are the specified lower and upper bounds. This may be an
1057empty sequence. It is not an error if $i$ or $j$ lie outside the
1058range of valid indexes (such items don't exist so they aren't
1059selected).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001060
1061\subsection{Calls}
1062
1063A call calls a function with a possibly empty series of arguments:
1064
1065\begin{verbatim}
1066call: primary "(" [condition_list] ")"
1067\end{verbatim}
1068
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001069The primary must evaluate to a callable object (user-defined
1070functions, built-in functions, methods of built-in objects, class
1071objects, and methods of class instances are callable). If it is a
1072class, the argument list must be empty.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001073
1074XXX explain what happens on function call
1075
Guido van Rossumf2612d11991-11-21 13:53:03 +00001076\section{Factors}
1077
1078Factors represent the unary numeric operators.
1079Their syntax is:
1080
1081\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001082factor: primary | "-" factor | "+" factor | "~" factor
Guido van Rossumf2612d11991-11-21 13:53:03 +00001083\end{verbatim}
1084
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001085The unary \verb\"-"\ operator yields the negative of its
1086numeric argument.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001087
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001088The unary \verb\"+"\ operator yields its numeric argument unchanged.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001089
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001090The unary \verb\"~"\ operator yields the bit-wise negation of its
1091plain or long integer argument. The bit-wise negation negation of
1092\verb\x\ is defined as \verb\-(x+1)\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001093
1094In all three cases, if the argument does not have the proper type,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001095a \verb\TypeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001096
1097\section{Terms}
1098
1099Terms represent the most tightly binding binary operators:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001100%
Guido van Rossumf2612d11991-11-21 13:53:03 +00001101\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001102term: factor | term "*" factor | term "/" factor | term "%" factor
Guido van Rossumf2612d11991-11-21 13:53:03 +00001103\end{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001104%
1105The \verb\"*"\ (multiplication) operator yields the product of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001106arguments. The arguments must either both be numbers, or one argument
1107must be a plain integer and the other must be a sequence. In the
1108former case, the numbers are converted to a common type and then
1109multiplied together. In the latter case, sequence repetition is
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001110performed; a negative repetition factor yields an empty sequence.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001111
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001112The \verb\"/"\ (division) operator yields the quotient of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001113arguments. The numeric arguments are first converted to a common
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001114type. Plain or long integer division yields an integer of the same
1115type; the result is that of mathematical division with the `floor'
1116function applied to the result. Division by zero raises the
1117\verb\ZeroDivisionError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001118
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001119The \verb\"%"\ (modulo) operator yields the remainder from the
Guido van Rossum670e5a01992-01-17 14:03:20 +00001120division of the first argument by the second. The numeric arguments
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001121are first converted to a common type. A zero right argument raises the
1122\verb\ZeroDivisionError\ exception. The arguments may be floating point
1123numbers, e.g., \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo operator
Guido van Rossum670e5a01992-01-17 14:03:20 +00001124always yields a result with the same sign as its second operand (or
1125zero); the absolute value of the result is strictly smaller than the
1126second operand.
1127
1128The integer division and modulo operators are connected by the
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001129following identity: \verb\x == (x/y)*y + (x%y)\.
1130Integer division and modulo are also connected with the built-in
1131function \verb\divmod()\: \verb\divmod(x, y) == (x/y, x%y)\.
1132These identities don't hold for floating point numbers; there a
1133similar identity holds where \verb\x/y\ is replaced by
1134\verb\floor(x/y)\).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001135
1136\section{Arithmetic expressions}
1137
1138\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001139arith_expr: term | arith_expr "+" term | arith_expr "-" term
Guido van Rossumf2612d11991-11-21 13:53:03 +00001140\end{verbatim}
1141
Guido van Rossum670e5a01992-01-17 14:03:20 +00001142The \verb|"+"| operator yields the sum of its arguments. The
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001143arguments must either both be numbers, or both sequences of the same
1144type. In the former case, the numbers are converted to a common type
1145and then added together. In the latter case, the sequences are
1146concatenated.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001147
Guido van Rossum743d1e71992-01-07 16:43:53 +00001148The \verb|"-"| operator yields the difference of its arguments.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001149The numeric arguments are first converted to a common type.
1150
1151\section{Shift expressions}
1152
1153\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001154shift_expr: arith_expr | shift_expr ( "<<" | ">>" ) arith_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001155\end{verbatim}
1156
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001157These operators accept plain or long integers as arguments. The
1158arguments are converted to a common type. They shift the first
1159argument to the left or right by the number of bits given by the
1160second argument.
1161
1162A right shift by $n$ bits is defined as division by $2^n$. A left
1163shift by $n$ bits is defined as multiplication with $2^n$ without
1164overflow check; for plain integers this drops bits if the result is
1165not less than $2^{31} - 1$ in absolute value.
1166
1167Negative shift counts raise a \verb\ValueError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001168
1169\section{Bitwise AND expressions}
1170
1171\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001172and_expr: shift_expr | and_expr "&" shift_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001173\end{verbatim}
1174
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001175This operator yields the bitwise AND of its arguments, which must be
1176plain or long integers. The arguments are converted to a common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001177
1178\section{Bitwise XOR expressions}
1179
1180\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001181xor_expr: and_expr | xor_expr "^" and_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001182\end{verbatim}
1183
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001184This operator yields the bitwise exclusive OR of its arguments, which
1185must be plain or long integers. The arguments are converted to a
1186common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001187
1188\section{Bitwise OR expressions}
1189
1190\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001191or_expr: xor_expr | or_expr "|" xor_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001192\end{verbatim}
1193
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001194This operator yields the bitwise OR of its arguments, which must be
1195plain or long integers. The arguments are converted to a common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001196
1197\section{Comparisons}
1198
1199\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001200comparison: or_expr (comp_operator or_expr)*
Guido van Rossum743d1e71992-01-07 16:43:53 +00001201comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001202\end{verbatim}
1203
1204Comparisons yield integer value: 1 for true, 0 for false.
1205
1206Comparisons can be chained arbitrarily,
1207e.g., $x < y <= z$ is equivalent to
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001208$x < y$ \verb\and\ $y <= z$, except that $y$ is evaluated only once
Guido van Rossumf2612d11991-11-21 13:53:03 +00001209(but in both cases $z$ is not evaluated at all when $x < y$ is
1210found to be false).
1211
1212Formally, $e_0 op_1 e_1 op_2 e_2 ...e_{n-1} op_n e_n$ is equivalent to
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001213$e_0 op_1 e_1$ \verb\and\ $e_1 op_2 e_2$ \verb\and\ ... \verb\and\
Guido van Rossumf2612d11991-11-21 13:53:03 +00001214$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
1215
1216Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
1217between $e_0$ and $e_2$, e.g., $x < y > z$ is perfectly legal.
1218
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001219The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with
1220C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below
1221\verb\<>\ is also implied.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001222
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001223The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
Guido van Rossumf2612d11991-11-21 13:53:03 +00001224the values of two objects. The objects needn't have the same type.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001225If both are numbers, they are coverted to a common type. Otherwise,
1226objects of different types {\em always} compare unequal, and are
1227ordered consistently but arbitrarily.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001228
1229(This unusual
1230definition of comparison is done to simplify the definition of
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001231operations like sorting and the \verb\in\ and \verb\not in\ operators.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001232
1233Comparison of objects of the same type depends on the type:
1234
1235\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001236
1237\item
1238Numbers are compared arithmetically.
1239
1240\item
1241Strings are compared lexicographically using the numeric equivalents
1242(the result of the built-in function \verb\ord\) of their characters.
1243
1244\item
1245Tuples and lists are compared lexicographically using comparison of
1246corresponding items.
1247
1248\item
1249Mappings (dictionaries) are compared through lexicographic
1250comparison of their sorted (key, value) lists.%
1251\footnote{This is expensive since it requires sorting the keys first,
1252but about the only sensible definition. It was tried to compare
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001253dictionaries using the rule below for most other types, but this gave
1254surprises in cases like \verb|if d == {}: ...|.}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001255
1256\item
1257Most other types compare unequal unless they are the same object;
1258the choice whether one object is considered smaller or larger than
1259another one is made arbitrarily but consistently within one
1260execution of a program.
1261
Guido van Rossumf2612d11991-11-21 13:53:03 +00001262\end{itemize}
1263
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001264The operators \verb\in\ and \verb\not in\ test for sequence
1265membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and
1266only if there exists an index $i$ such that $x = y[i]$.
1267$x ~\verb\not in\~ y$ yields the inverse truth value. The exception
1268\verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is
1269a string and $x$ is not a string of length one.%
1270\footnote{The latter restriction is sometimes a nuisance.}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001271
1272The operators \verb\is\ and \verb\is not\ compare object identity:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001273$x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same
1274object. $x ~\verb\is not\~ y$ yields the inverse truth value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001275
1276\section{Boolean operators}
1277
1278\begin{verbatim}
1279condition: or_test
Guido van Rossum743d1e71992-01-07 16:43:53 +00001280or_test: and_test | or_test "or" and_test
1281and_test: not_test | and_test "and" not_test
1282not_test: comparison | "not" not_test
Guido van Rossumf2612d11991-11-21 13:53:03 +00001283\end{verbatim}
1284
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001285In the context of Boolean operators, and also when conditions are used
1286by control flow statements, the following values are interpreted as
1287false: \verb\None\, numeric zero of all types, empty sequences
1288(strings, tuples and lists), and empty mappings (dictionaries). All
1289other values are interpreted as true.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001290
1291The operator \verb\not\ yields 1 if its argument is false, 0 otherwise.
1292
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001293The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001294$x$ is returned; otherwise, $y$ is evaluated and returned.
1295
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001296The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001297$x$ is returned; otherwise, $y$ is evaluated and returned.
1298
1299(Note that \verb\and\ and \verb\or\ do not restrict the value and type
1300they return to 0 and 1, but rather return the last evaluated argument.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001301This is sometimes useful, e.g., if \verb\s\ is a string, which should be
1302replaced by a default value if it is empty, \verb\s or 'foo'\
Guido van Rossumf2612d11991-11-21 13:53:03 +00001303returns the desired value. Because \verb\not\ has to invent a value
1304anyway, it does not bother to return a value of the same type as its
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001305argument, so \verb\not 'foo'\ yields \verb\0\, not \verb\''\.)
1306
1307\section{Expression lists and condition lists}
1308
1309\begin{verbatim}
1310expr_list: or_expr ("," or_expr)* [","]
1311cond_list: condition ("," condition)* [","]
1312\end{verbatim}
1313
1314The only difference between expression lists and condition lists is
1315the lowest priority of operators that can be used in them without
1316being enclosed in parentheses; condition lists allow all operators,
1317while expression lists don't allow comparisons and Boolean operators
1318(they do allow bitwise and shift operators though).
1319
1320Expression lists are used in expression statements and assignments;
1321condition lists are used everywhere else.
1322
1323An expression (condition) list containing at least one comma yields a
1324tuple. The length of the tuple is the number of expressions
1325(conditions) in the list. The expressions (conditions) are evaluated
1326from left to right.
1327
1328The trailing comma is required only to create a single tuple (a.k.a. a
1329{\em singleton}); it is optional in all other cases. A single
1330expression (condition) without a trailing comma doesn't create a
1331tuple, but rather yields the value of that expression (condition).
1332
1333To create an empty tuple, use an empty pair of parentheses: \verb\()\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001334
1335\chapter{Simple statements}
1336
1337Simple statements are comprised within a single logical line.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001338Several simple statements may occur on a single line separated
Guido van Rossumf2612d11991-11-21 13:53:03 +00001339by semicolons. The syntax for simple statements is:
1340
1341\begin{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001342simple_stmt: expression_stmt
1343 | assignment
1344 | pass_stmt
1345 | del_stmt
1346 | print_stmt
1347 | return_stmt
1348 | raise_stmt
1349 | break_stmt
1350 | continue_stmt
1351 | import_stmt
Guido van Rossum743d1e71992-01-07 16:43:53 +00001352 | global_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001353\end{verbatim}
1354
1355\section{Expression statements}
1356
1357\begin{verbatim}
1358expression_stmt: expression_list
1359\end{verbatim}
1360
1361An expression statement evaluates the expression list (which may
1362be a single expression).
1363If the value is not \verb\None\, it is converted to a string
1364using the rules for string conversions, and the resulting string
1365is written to standard output on a line by itself.
1366
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001367(The exception for \verb\None\ is made so that procedure calls, which
1368are syntactically equivalent to expressions, do not cause any output.
1369A tuple with only \verb\None\ items is written normally.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001370
1371\section{Assignments}
1372
1373\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001374assignment: (target_list "=")+ expression_list
Guido van Rossum743d1e71992-01-07 16:43:53 +00001375target_list: target ("," target)* [","]
1376target: identifier | "(" target_list ")" | "[" target_list "]"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001377 | attributeref | subscription | slicing
1378\end{verbatim}
1379
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001380(See the section on primaries for the syntax definition of the last
Guido van Rossumf2612d11991-11-21 13:53:03 +00001381three symbols.)
1382
1383An assignment evaluates the expression list (remember that this can
1384be a single expression or a comma-separated list,
1385the latter yielding a tuple)
1386and assigns the single resulting object to each of the target lists,
1387from left to right.
1388
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001389Assignment is defined recursively depending on the form of the target.
1390When a target is part of a mutable object (an attribute reference,
1391subscription or slicing), the mutable object must ultimately perform
1392the assignment and decide about its validity, and may raise an
1393exception if the assignment is unacceptable. The rules observed by
1394various types and the exceptions raised are given with the definition
1395of the object types (some of which are defined in the library
1396reference).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001397
1398Assignment of an object to a target list is recursively
1399defined as follows.
1400
1401\begin{itemize}
1402\item
1403If the target list contains no commas (except in nested constructs):
1404the object is assigned to the single target contained in the list.
1405
1406\item
1407If the target list contains commas (that are not in nested constructs):
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001408the object must be a tuple with the same number of items
Guido van Rossumf2612d11991-11-21 13:53:03 +00001409as the list contains targets, and the items are assigned, from left
1410to right, to the corresponding targets.
1411
1412\end{itemize}
1413
1414Assignment of an object to a (non-list)
1415target is recursively defined as follows.
1416
1417\begin{itemize}
1418
1419\item
1420If the target is an identifier (name):
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001421\begin{itemize}
1422\item
1423If the name does not occur in a \verb\global\ statement in the current
1424code block: the object is bound to that name in the current local
1425name space.
1426\item
1427Otherwise: the object is bound to that name in the current global name
1428space.
1429\end{itemize}
1430A previous binding of the same name in the same name space is undone.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001431
1432\item
1433If the target is a target list enclosed in parentheses:
1434the object is assigned to that target list.
1435
1436\item
1437If the target is a target list enclosed in square brackets:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001438the object must be a list with the same number of items
Guido van Rossumf2612d11991-11-21 13:53:03 +00001439as the target list contains targets,
1440and the list's items are assigned, from left to right,
1441to the corresponding targets.
1442
1443\item
1444If the target is an attribute reference:
1445The primary expression in the reference is evaluated.
1446It should yield an object with assignable attributes;
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001447if this is not the case, \verb\TypeError\ is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001448That object is then asked to assign the assigned object
1449to the given attribute; if it cannot perform the assignment,
1450it raises an exception.
1451
1452\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001453If the target is a subscription: The primary expression in the
1454reference is evaluated. It should yield either a mutable sequence
1455(list) object or a mapping (dictionary) object. Next, the subscript
1456expression is evaluated.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001457
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001458If the primary is a sequence object, the subscript must yield a plain
1459integer. If it is negative, the sequence's length is added to it.
1460The resulting value must be a nonnegative integer less than the
1461sequence's length, and the sequence is asked to assign the assigned
1462object to its item with that index. If the index is out of range,
1463\verb\IndexError\ is raised (assignment to a subscripted sequence
1464cannot add new items to a list).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001465
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001466If the primary is a mapping object, the subscript must have a type
1467compatible with the mapping's key type, and the mapping is then asked
1468to to create a key/datum pair which maps the subscript to the assigned
1469object. This can either replace an existing key/value pair with the
1470same key value, or insert a new key/value pair (if no key with the
1471same value existed).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001472
1473\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001474If the target is a slicing: The primary expression in the reference is
1475evaluated. It should yield a mutable sequence (list) object. The
1476assigned object should be a sequence object of the same type. Next,
1477the lower and upper bound expressions are evaluated, insofar they are
1478present; defaults are zero and the sequence's length. The bounds
1479should evaluate to (small) integers. If either bound is negative, the
1480sequence's length is added to it. The resulting bounds are clipped to
1481lie between zero and the sequence's length, inclusive. Finally, the
1482sequence object is asked to replace the items indicated by the slice
1483with the items of the assigned sequence. This may change the
1484sequence's length, if it allows it.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001485
1486\end{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001487
Guido van Rossumf2612d11991-11-21 13:53:03 +00001488(In the original implementation, the syntax for targets is taken
1489to be the same as for expressions, and invalid syntax is rejected
1490during the code generation phase, causing less detailed error
1491messages.)
1492
Guido van Rossum68c172e1992-01-21 11:34:56 +00001493\section{The {\tt pass} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001494
1495\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001496pass_stmt: "pass"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001497\end{verbatim}
1498
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001499\verb\pass\ is a null operation -- when it is executed, nothing
1500happens. It is useful as a placeholder when a statement is
1501required syntactically, but no code needs to be executed, for example:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001502
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001503\begin{verbatim}
1504def f(arg): pass # a no-op function
1505
1506class C: pass # an empty class
1507\end{verbatim}
1508
Guido van Rossum68c172e1992-01-21 11:34:56 +00001509\section{The {\tt del} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001510
1511\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001512del_stmt: "del" target_list
Guido van Rossumf2612d11991-11-21 13:53:03 +00001513\end{verbatim}
1514
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001515Deletion is recursively defined very similar to the way assignment is
1516defined. Rather that spelling it out in full details, here are some
1517hints.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001518
1519Deletion of a target list recursively deletes each target,
1520from left to right.
1521
1522Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001523from the local or global name space, depending on whether the name
1524occurs in a \verb\global\ statement in the same code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001525
1526Deletion of attribute references, subscriptions and slicings
1527is passed to the primary object involved; deletion of a slicing
1528is in general equivalent to assignment of an empty slice of the
1529right type (but even this is determined by the sliced object).
1530
Guido van Rossum68c172e1992-01-21 11:34:56 +00001531\section{The {\tt print} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001532
1533\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001534print_stmt: "print" [ condition ("," condition)* [","] ]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001535\end{verbatim}
1536
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001537\verb\print\ evaluates each condition in turn and writes the resulting
1538object to standard output (see below). If an object is not a string,
1539it is first converted to a string using the rules for string
1540conversions. The (resulting or original) string is then written. A
1541space is written before each object is (converted and) written, unless
1542the output system believes it is positioned at the beginning of a
1543line. This is the case: (1) when no characters have yet been written
1544to standard output; or (2) when the last character written to standard
1545output is \verb/\n/; or (3) when the last write operation on standard
1546output was not a \verb\print\ statement. (In some cases it may be
1547functional to write an empty string to standard output for this
1548reason.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001549
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001550A \verb/"\n"/ character is written at the end, unless the \verb\print\
1551statement ends with a comma. This is the only action if the statement
1552contains just the keyword \verb\print\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001553
1554Standard output is defined as the file object named \verb\stdout\
1555in the built-in module \verb\sys\. If no such object exists,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001556or if it is not a writable file, a \verb\RuntimeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001557(The original implementation attempts to write to the system's original
1558standard output instead, but this is not safe, and should be fixed.)
1559
Guido van Rossum68c172e1992-01-21 11:34:56 +00001560\section{The {\tt return} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001561
1562\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001563return_stmt: "return" [condition_list]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001564\end{verbatim}
1565
1566\verb\return\ may only occur syntactically nested in a function
1567definition, not within a nested class definition.
1568
1569If a condition list is present, it is evaluated, else \verb\None\
1570is substituted.
1571
1572\verb\return\ leaves the current function call with the condition
1573list (or \verb\None\) as return value.
1574
1575When \verb\return\ passes control out of a \verb\try\ statement
1576with a \verb\finally\ clause, that finally clause is executed
1577before really leaving the function.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001578
Guido van Rossum68c172e1992-01-21 11:34:56 +00001579\section{The {\tt raise} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001580
1581\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001582raise_stmt: "raise" condition ["," condition]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001583\end{verbatim}
1584
1585\verb\raise\ evaluates its first condition, which must yield
1586a string object. If there is a second condition, this is evaluated,
1587else \verb\None\ is substituted.
1588
1589It then raises the exception identified by the first object,
1590with the second one (or \verb\None\) as its parameter.
1591
Guido van Rossum68c172e1992-01-21 11:34:56 +00001592\section{The {\tt break} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001593
1594\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001595break_stmt: "break"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001596\end{verbatim}
1597
1598\verb\break\ may only occur syntactically nested in a \verb\for\
1599or \verb\while\ loop, not nested in a function or class definition.
1600
1601It terminates the neares enclosing loop, skipping the optional
1602\verb\else\ clause if the loop has one.
1603
1604If a \verb\for\ loop is terminated by \verb\break\, the loop control
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001605target keeps its current value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001606
1607When \verb\break\ passes control out of a \verb\try\ statement
1608with a \verb\finally\ clause, that finally clause is executed
1609before really leaving the loop.
1610
Guido van Rossum68c172e1992-01-21 11:34:56 +00001611\section{The {\tt continue} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001612
1613\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001614continue_stmt: "continue"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001615\end{verbatim}
1616
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001617\verb\continue\ may only occur syntactically nested in a \verb\for\ or
1618\verb\while\ loop, not nested in a function or class definition, and
1619not nested in the \verb\try\ clause of a \verb\try\ statement with a
1620\verb\finally\ clause (it may occur nested in a \verb\except\ or
1621\verb\finally\ clause of a \verb\try\ statement though).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001622
1623It continues with the next cycle of the nearest enclosing loop.
1624
Guido van Rossum862c6f11992-01-29 14:47:05 +00001625\section{The {\tt import} statement} \label{import}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001626
1627\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001628import_stmt: "import" identifier ("," identifier)*
1629 | "from" identifier "import" identifier ("," identifier)*
1630 | "from" identifier "import" "*"
1631\end{verbatim}
1632
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001633Import statements are executed in two steps: (1) find a module, and
1634initialize it if necessary; (2) define a name or names in the local
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001635name space (of the scope where the \verb\import\ statement occurs).
1636The first form (without \verb\from\) repeats these steps for each
1637identifier in the list, the \verb\from\ form performs them once, with
1638the first identifier specifying the module name.
Guido van Rossum743d1e71992-01-07 16:43:53 +00001639
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001640The system maintains a table of modules that have been initialized,
1641indexed by module name. (The current implementation makes this table
1642accessible as \verb\sys.modules\.) When a module name is found in
1643this table, step (1) is finished. If not, a search for a module
1644definition is started. This first looks for a built-in module
1645definition, and if no built-in module if the given name is found, it
1646searches a user-specified list of directories for a file whose name is
1647the module name with extension \verb\".py"\. (The current
1648implementation uses the list of strings \verb\sys.path\ as the search
1649path; it is initialized from the shell environment variable
1650\verb\$PYTHONPATH\, with an installation-dependent default.)
1651
1652If a built-in module is found, its built-in initialization code is
1653executed and step (1) is finished. If no matching file is found,
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001654\verb\ImportError\ is raised. If a file is found, it is parsed,
1655yielding an executable code block. If a syntax error occurs,
1656\verb\SyntaxError\ is raised. Otherwise, an empty module of the given
1657name is created and inserted in the module table, and then the code
1658block is executed in the context of this module. Exceptions during
1659this execution terminate step (1).
1660
1661When step (1) finishes without raising an exception, step (2) can
1662begin.
1663
1664The first form of \verb\import\ statement binds the module name in the
1665local name space to the module object, and then goes on to import the
1666next identifier, if any. The \verb\from\ from does not bind the
1667module name: it goes through the list of identifiers, looks each one
1668of them up in the module found in step (1), and binds the name in the
1669local name space to the object thus found. If a name is not found,
1670\verb\ImportError\ is raised. If the list of identifiers is replaced
1671by a star (\verb\*\), all names defined in the module are bound,
1672except those beginning with an underscore(\verb\_\).
1673
1674Names bound by import statements may not occur in \verb\global\
1675statements in the same scope.
1676
1677The \verb\from\ form with \verb\*\ may only occur in a module scope.
1678
1679(The current implementation does not enforce the latter two
1680restrictions, but programs should not abuse this freedom, as future
1681implementations may enforce them or silently change the meaning of the
1682program.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001683
Guido van Rossum862c6f11992-01-29 14:47:05 +00001684\section{The {\tt global} statement} \label{global}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001685
1686\begin{verbatim}
1687global_stmt: "global" identifier ("," identifier)*
Guido van Rossumf2612d11991-11-21 13:53:03 +00001688\end{verbatim}
1689
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001690The \verb\global\ statement is a declaration which holds for the
1691entire current scope. It means that the listed identifiers are to be
1692interpreted as globals. While {\em using} global names is automatic
1693if they are not defined in the local scope, {\em assigning} to global
1694names would be impossible without \verb\global\.
1695
1696Names listed in a \verb\global\ statement must not be used in the same
1697scope before that \verb\global\ statement is executed.
1698
1699Name listed in a \verb\global\ statement must not be defined as formal
1700parameters or in a \verb\for\ loop control target, \verb\class\
1701definition, function definition, or \verb\import\ statement.
1702
1703(The current implementation does not enforce the latter two
1704restrictions, but programs should not abuse this freedom, as future
1705implementations may enforce them or silently change the meaning of the
1706program.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001707
1708\chapter{Compound statements}
1709
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001710Compound statements contain (groups of) other statements; they affect
1711or control the execution of those other statements in some way.
1712
1713The \verb\if\, \verb\while\ and \verb\for\ statements implement
1714traditional control flow constructs. \verb\try\ specifies exception
1715handlers and/or cleanup code for a group of statements. Function and
1716class definitions are also syntactically compound statements.
1717
1718Compound statements consist of one or more `clauses'. A clause
1719consists of a header and a `suite'. The clause headers of a
1720particular compound statement are all at the same indentation level;
1721all clauses begin with a uniquely identifying keyword and end with a
1722colon. A suite is a group of statements controlled by a clause. A
1723suite can be a bunch of semicolon-separated simple statements on the
1724same line as the header, following the colon, or it can be a list of
1725indented statements. Only the latter form of suite can contain nested
1726compound statements; the following is illegal (mostly because it
1727wouldn't be clear what to do with \verb\else\):
Guido van Rossumf2612d11991-11-21 13:53:03 +00001728
1729\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001730if test1: if test2: print x
Guido van Rossumf2612d11991-11-21 13:53:03 +00001731\end{verbatim}
1732
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001733Also note that the semicolon binds tighter that the colon in this
1734context (so to speak), so that in the following example, either all or
1735none of the \verb\print\ statements are executed:
1736
1737\begin{verbatim}
1738if some_test: print x; print y; print z
1739\end{verbatim}
1740
1741Summarizing:
1742
1743\begin{verbatim}
1744compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1745suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
1746statement: stmt_list NEWLINE | compound_stmt
1747stmt_list: simple_stmt (";" simple_stmt)* [";"]
1748\end{verbatim}
1749
1750Note that statements always ends in a \verb\NEWLINE\ possibly followed
1751by a \verb\DEDENT\.
1752
1753Also note that optional continuation clauses always begin with a
1754keyword that cannot start a statement, thus there are no ambiguities
1755(the `dangling \verb\else\' problem is solved in Python by requiring
1756nested \verb\if\ statements to be indented).
1757
1758The formatting of the grammar rules in the following section places
1759each clause on a separate line for clarity.
1760
Guido van Rossum68c172e1992-01-21 11:34:56 +00001761\section{The {\tt if} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001762
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001763The \verb\if\ statement is used for conditional execution:
1764
Guido van Rossumf2612d11991-11-21 13:53:03 +00001765\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001766if_stmt: "if" condition ":" suite
1767 ("elif" condition ":" suite)*
1768 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001769\end{verbatim}
1770
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001771It selects exactly one of the suites, by testing the conditions one by
1772one until one is true; then that suite is executed. If all conditions
1773are false, the suite of the \verb\else\ clause is executed, if present.
1774
Guido van Rossum68c172e1992-01-21 11:34:56 +00001775\section{The {\tt while} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001776
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001777The \verb\while\ statement is used for repeated execution as long as a
1778condition is true:
1779
Guido van Rossumf2612d11991-11-21 13:53:03 +00001780\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001781while_stmt: "while" condition ":" suite
1782 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001783\end{verbatim}
1784
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001785This repeatedly tests the condition and, if it is true, executes the
1786first suite; if the condition is false (which may be the first time it
1787is tested) the suite of the \verb\else\ clause is executed, if
1788present, and the loop terminates.
1789
1790A \verb\break\ statement executed in the first suite terminates the
1791loop without executing the \verb\else\ clause's suite. A
1792\verb\continue\ statement executed in the first suited skips the rest
1793of the suite and goes back to testing the condition.
1794
Guido van Rossum68c172e1992-01-21 11:34:56 +00001795\section{The {\tt for} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001796
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001797The \verb\for\ statement is used to iterate over the elements of a
1798sequence (string, tuple or list):
1799
Guido van Rossumf2612d11991-11-21 13:53:03 +00001800\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001801for_stmt: "for" target_list "in" condition_list ":" suite
1802 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001803\end{verbatim}
1804
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001805The suite is executed once for each item in the condition list, in the
1806order of ascending indices. Each item in turn is assigned to the
1807target list using the standard rules for assignments, and then the
1808suite is executed. When the list is exhausted (which is immediately
1809when the sequence is empty), the suite in the \verb\else\ clause is
1810executed, if present.
1811
1812A \verb\break\ statement executed in the first suite terminates the
1813loop without executing the \verb\else\ clause's suite. A
1814\verb\continue\ statement executed in the first suited skips the rest
1815of the suite and continues with the next item or with the \verb\else\
1816clause.
1817
1818The suite may assign to the variable(s) in the target list; this does
1819not affect the next item assigned to it.
1820
1821The target list are not deleted when the loop is finished (but if the
1822loop has executed 0 times it will not have been assigned to at all by
1823the loop).
1824
1825The built-in function \verb\range()\ returns a sequence of integers
1826suitable to emulate the effect of Pascal's \verb\for i := 1 to n do\.
1827
1828{\bf Warning:} There is a subtlety when the sequence is being modified
1829by the loop (this can only occur for lists). An internal counter is
1830used to keep track of which item is used next, and this is incremented
1831on each iteration. When this counter has reached the end of the
1832sequence the loop terminates. This means that if the suite deletes
1833the current (or a previous) item from the sequence, the next item will
1834be skipped (since it gets the index of the current item and this has
1835already been treated). Likewise, if the suite inserts an item in the
1836sequence before the current item, the current item will be treated
1837again the next time through the loop. This can lead to nasty bugs
1838that can be avoided by making a temporary copy using the \
1839
Guido van Rossum68c172e1992-01-21 11:34:56 +00001840\section{The {\tt try} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001841
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001842The \verb\try\ statement specifies exception handlers and/or cleanup
1843code for a group of statements:
1844
Guido van Rossumf2612d11991-11-21 13:53:03 +00001845\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001846try_stmt: "try" ":" suite
1847 ("except" condition ["," condition] ":" suite)*
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001848 ["except" ":" suite]
Guido van Rossum743d1e71992-01-07 16:43:53 +00001849 ["finally" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001850\end{verbatim}
1851
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001852There are really two forms: \verb\try...except\ and
1853\verb\try...finally\. A \verb\try\ statement with both types of
1854clauses is equivalent to a \verb\try...finally\ statement with a
1855\verb\try...except\ statement in its \verb\try\ clause. A \verb\try\
1856statement with neither a \verb\except\ clause nor a \verb\finally\
1857clause just executes the suite of statements in its \verb\try\ clause.
1858
1859The \verb\try...except\ form specifies one or more exception handlers.
1860When no exception occurs in the \verb\try\ clause, no exception
1861handler is executed. When an exception occurs in the \verb\try\
1862suite, a search for an exception handler HIRO
1863
1864The \verb\try...finally\ form specifies a `cleanup' handler. The
1865\verb\try\ clause is executed. When no exception occurs, the
1866\verb\finally\ clause is executed. When an exception occurs on the
1867\verb\try\ clause, the exception is temporarily saved, the
1868\verb\finally\ clause is executed, and then the saved exception is
1869re-raised. If the \verb\finally\ clause raises another exception or
1870executes a \verb\return\, \verb\break\ or \verb\continue\ statement,
1871the saved exception is lost.
1872
1873When a \verb\return\ or \verb\break\ statement is executed in the
1874\verb\try suite of a \verb\try...finally\ statement, the
1875\verb\finally\ clause is also executed `on the way out'. A
1876\verb\continue\ statement is illegal in the \verb\try\ clause (the
1877reason is a problem with the current implementation -- this
1878restriction may be lifted in the future).
1879
Guido van Rossum862c6f11992-01-29 14:47:05 +00001880\section{Function definitions} \label{function}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001881
Guido van Rossum862c6f11992-01-29 14:47:05 +00001882XXX
Guido van Rossumf2612d11991-11-21 13:53:03 +00001883
1884\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001885funcdef: "def" identifier "(" [parameter_list] ")" ":" suite
1886parameter_list: parameter ("," parameter)*
1887parameter: identifier | "(" parameter_list ")"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001888\end{verbatim}
1889
Guido van Rossum862c6f11992-01-29 14:47:05 +00001890XXX
1891
1892\section{Class definitions} \label{class}
1893
1894XXX
Guido van Rossumf2612d11991-11-21 13:53:03 +00001895
1896\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001897classdef: "class" identifier [inheritance] ":" suite
1898inheritance: "(" expression ("," expression)* ")"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001899\end{verbatim}
1900
Guido van Rossum862c6f11992-01-29 14:47:05 +00001901XXX
1902
1903\section{P.M.}
1904
Guido van Rossumf2612d11991-11-21 13:53:03 +00001905XXX Syntax for scripts, modules
1906XXX Syntax for interactive input, eval, exec, input
Guido van Rossum743d1e71992-01-07 16:43:53 +00001907XXX New definition of expressions (as conditions)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001908
1909\end{document}