blob: 69b6e96d6183b0e520c1e8186e65db19a79a3d5e [file] [log] [blame]
Guido van Rossum60279da1992-04-02 10:24:59 +00001\documentstyle[twoside,a4wide,11pt,myformat]{report}
2% ^^^^^^^^^^^^^^^^^^^^
3% If you have trouble finding these style files, any of the pointed-at
4% style options are optional and may be taken out.
5% But "myformat.sty" should be found in the same directory as this file!
6% Also, "myformat" should be last since it corrects a few style params.
Guido van Rossumf2612d11991-11-21 13:53:03 +00007
Guido van Rossum862c6f11992-01-29 14:47:05 +00008\title{\bf Python Reference Manual}
9
Guido van Rossumf2612d11991-11-21 13:53:03 +000010\author{
11 Guido van Rossum \\
12 Dept. CST, CWI, Kruislaan 413 \\
13 1098 SJ Amsterdam, The Netherlands \\
14 E-mail: {\tt guido@cwi.nl}
15}
16
Guido van Rossumb5e1c181992-03-06 10:52:59 +000017% Tell \index to actually write the .idx file
18\makeindex
19
Guido van Rossumf2612d11991-11-21 13:53:03 +000020\begin{document}
21
22\pagenumbering{roman}
23
24\maketitle
25
26\begin{abstract}
27
28\noindent
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000029Python is a simple, yet powerful, interpreted programming language
30that bridges the gap between C and shell programming, and is thus
31ideally suited for ``throw-away programming'' and rapid prototyping.
32Its syntax is put together from constructs borrowed from a variety of
33other languages; most prominent are influences from ABC, C, Modula-3
34and Icon.
Guido van Rossumf2612d11991-11-21 13:53:03 +000035
36The Python interpreter is easily extended with new functions and data
37types implemented in C. Python is also suitable as an extension
38language for highly customizable C applications such as editors or
39window managers.
40
41Python is available for various operating systems, amongst which
42several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S.,
43and MS-DOS.
44
45This reference manual describes the syntax and ``core semantics'' of
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000046the language. It is terse, but attempts to be exact and complete.
47The semantics of non-essential built-in object types and of the
48built-in functions and modules are described in the {\em Python
49Library Reference}. For an informal introduction to the language, see
50the {\em Python Tutorial}.
Guido van Rossumf2612d11991-11-21 13:53:03 +000051
52\end{abstract}
53
54\pagebreak
55
Guido van Rossum670e5a01992-01-17 14:03:20 +000056{
57\parskip = 0mm
Guido van Rossumf2612d11991-11-21 13:53:03 +000058\tableofcontents
Guido van Rossum670e5a01992-01-17 14:03:20 +000059}
Guido van Rossumf2612d11991-11-21 13:53:03 +000060
61\pagebreak
62
63\pagenumbering{arabic}
64
65\chapter{Introduction}
66
67This reference manual describes the Python programming language.
68It is not intended as a tutorial.
69
Guido van Rossum743d1e71992-01-07 16:43:53 +000070While I am trying to be as precise as possible, I chose to use English
71rather than formal specifications for everything except syntax and
72lexical analysis. This should make the document better understandable
73to the average reader, but will leave room for ambiguities.
74Consequently, if you were coming from Mars and tried to re-implement
Guido van Rossum7b632a61992-01-16 17:49:21 +000075Python from this document alone, you might have to guess things and in
Guido van Rossumb5e1c181992-03-06 10:52:59 +000076fact you would probably end up implementing quite a different language.
Guido van Rossum7b632a61992-01-16 17:49:21 +000077On the other hand, if you are using
Guido van Rossum743d1e71992-01-07 16:43:53 +000078Python and wonder what the precise rules about a particular area of
Guido van Rossumb5e1c181992-03-06 10:52:59 +000079the language are, you should definitely be able to find them here.
Guido van Rossum743d1e71992-01-07 16:43:53 +000080
81It is dangerous to add too many implementation details to a language
Guido van Rossumb5e1c181992-03-06 10:52:59 +000082reference document --- the implementation may change, and other
Guido van Rossum743d1e71992-01-07 16:43:53 +000083implementations of the same language may work differently. On the
84other hand, there is currently only one Python implementation, and
Guido van Rossum7b632a61992-01-16 17:49:21 +000085its particular quirks are sometimes worth being mentioned, especially
Guido van Rossumb5e1c181992-03-06 10:52:59 +000086where the implementation imposes additional limitations. Therefore,
87you'll find short ``implementation notes'' sprinkled throughout the
88text.
Guido van Rossum743d1e71992-01-07 16:43:53 +000089
90Every Python implementation comes with a number of built-in and
91standard modules. These are not documented here, but in the separate
92{\em Python Library Reference} document. A few built-in modules are
93mentioned when they interact in a significant way with the language
94definition.
95
96\section{Notation}
97
98The descriptions of lexical analysis and syntax use a modified BNF
99grammar notation. This uses the following style of definition:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000100\index{BNF}
101\index{grammar}
102\index{syntax}
103\index{notation}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000104
105\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000106name: lc_letter (lc_letter | "_")*
107lc_letter: "a"..."z"
Guido van Rossum743d1e71992-01-07 16:43:53 +0000108\end{verbatim}
109
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000110The first line says that a \verb\name\ is an \verb\lc_letter\ followed by
111a sequence of zero or more \verb\lc_letter\s and underscores. An
112\verb\lc_letter\ in turn is any of the single characters `a' through `z'.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000113(This rule is actually adhered to for the names defined in lexical and
Guido van Rossum743d1e71992-01-07 16:43:53 +0000114grammar rules in this document.)
115
116Each rule begins with a name (which is the name defined by the rule)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000117and a colon. A vertical bar
Guido van Rossum7b632a61992-01-16 17:49:21 +0000118(\verb\|\) is used to separate alternatives; it is the least binding
119operator in this notation. A star (\verb\*\) means zero or more
120repetitions of the preceding item; likewise, a plus (\verb\+\) means
121one or more repetitions, and a question mark (\verb\?\) zero or one
122(in other words, the preceding item is optional). These three
123operators bind as tightly as possible; parentheses are used for
Guido van Rossum743d1e71992-01-07 16:43:53 +0000124grouping. Literal strings are enclosed in double quotes. White space
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000125is only meaningful to separate tokens. Rules are normally contained
126on a single line; rules with many alternatives may be formatted
127alternatively with each line after the first beginning with a
128vertical bar.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000129
130In lexical definitions (as the example above), two more conventions
131are used: Two literal characters separated by three dots mean a choice
132of any single character in the given (inclusive) range of ASCII
133characters. A phrase between angular brackets (\verb\<...>\) gives an
134informal description of the symbol defined; e.g., this could be used
135to describe the notion of `control character' if needed.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000136\index{lexical definitions}
137\index{ASCII}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000138
Guido van Rossum7b632a61992-01-16 17:49:21 +0000139Even though the notation used is almost the same, there is a big
Guido van Rossum743d1e71992-01-07 16:43:53 +0000140difference between the meaning of lexical and syntactic definitions:
141a lexical definition operates on the individual characters of the
142input source, while a syntax definition operates on the stream of
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000143tokens generated by the lexical analysis. All uses of BNF in the next
144chapter (``Lexical Analysis'') are lexical definitions; uses in
145subsequenc chapter are syntactic definitions.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000146
Guido van Rossumf2612d11991-11-21 13:53:03 +0000147\chapter{Lexical analysis}
148
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000149A Python program is read by a {\em parser}. Input to the parser is a
150stream of {\em tokens}, generated by the {\em lexical analyzer}. This
151chapter describes how the lexical analyzer breaks a file into tokens.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000152\index{lexical analysis}
153\index{parser}
154\index{token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000155
156\section{Line structure}
157
Guido van Rossum7b632a61992-01-16 17:49:21 +0000158A Python program is divided in a number of logical lines. The end of
159a logical line is represented by the token NEWLINE. Statements cannot
160cross logical line boundaries except where NEWLINE is allowed by the
161syntax (e.g., between statements in compound statements).
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000162\index{line structure}
163\index{logical line}
164\index{NEWLINE token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000165
166\subsection{Comments}
167
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000168A comment starts with a hash character (\verb\#\) that is not part of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000169a string literal, and ends at the end of the physical line. A comment
170always signifies the end of the logical line. Comments are ignored by
171the syntax.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000172\index{comment}
173\index{logical line}
174\index{physical line}
175\index{hash character}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000176
177\subsection{Line joining}
178
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000179Two or more physical lines may be joined into logical lines using
Guido van Rossum7b632a61992-01-16 17:49:21 +0000180backslash characters (\verb/\/), as follows: when a physical line ends
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000181in a backslash that is not part of a string literal or comment, it is
182joined with the following forming a single logical line, deleting the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000183backslash and the following end-of-line character. For example:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000184\index{physical line}
185\index{line joining}
186\index{backslash character}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000187%
188\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000189moth_names = ['Januari', 'Februari', 'Maart', \
190 'April', 'Mei', 'Juni', \
191 'Juli', 'Augustus', 'September', \
192 'Oktober', 'November', 'December']
Guido van Rossum670e5a01992-01-17 14:03:20 +0000193\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000194
195\subsection{Blank lines}
196
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000197A logical line that contains only spaces, tabs, and possibly a
198comment, is ignored (i.e., no NEWLINE token is generated), except that
199during interactive input of statements, an entirely blank logical line
200terminates a multi-line statement.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000201\index{blank line}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000202
203\subsection{Indentation}
204
Guido van Rossum7b632a61992-01-16 17:49:21 +0000205Leading whitespace (spaces and tabs) at the beginning of a logical
206line is used to compute the indentation level of the line, which in
207turn is used to determine the grouping of statements.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000208\index{indentation}
209\index{whitespace}
210\index{leading whitespace}
211\index{space}
212\index{tab}
213\index{grouping}
214\index{statement grouping}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000215
Guido van Rossum7b632a61992-01-16 17:49:21 +0000216First, tabs are replaced (from left to right) by one to eight spaces
217such that the total number of characters up to there is a multiple of
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000218eight (this is intended to be the same rule as used by {\UNIX}). The
Guido van Rossum7b632a61992-01-16 17:49:21 +0000219total number of spaces preceding the first non-blank character then
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000220determines the line's indentation. Indentation cannot be split over
221multiple physical lines using backslashes.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000222
223The indentation levels of consecutive lines are used to generate
224INDENT and DEDENT tokens, using a stack, as follows.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000225\index{INDENT token}
226\index{DEDENT token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000227
228Before the first line of the file is read, a single zero is pushed on
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000229the stack; this will never be popped off again. The numbers pushed on
230the stack will always be strictly increasing from bottom to top. At
231the beginning of each logical line, the line's indentation level is
232compared to the top of the stack. If it is equal, nothing happens.
233If it larger, it is pushed on the stack, and one INDENT token is
234generated. If it is smaller, it {\em must} be one of the numbers
235occurring on the stack; all numbers on the stack that are larger are
236popped off, and for each number popped off a DEDENT token is
237generated. At the end of the file, a DEDENT token is generated for
238each number remaining on the stack that is larger than zero.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000239
Guido van Rossum7b632a61992-01-16 17:49:21 +0000240Here is an example of a correctly (though confusingly) indented piece
241of Python code:
242
243\begin{verbatim}
244def perm(l):
Guido van Rossum670e5a01992-01-17 14:03:20 +0000245 # Compute the list of all permutations of l
246
Guido van Rossum7b632a61992-01-16 17:49:21 +0000247 if len(l) <= 1:
248 return [l]
249 r = []
250 for i in range(len(l)):
251 s = l[:i] + l[i+1:]
252 p = perm(s)
253 for x in p:
254 r.append(l[i:i+1] + x)
255 return r
256\end{verbatim}
257
258The following example shows various indentation errors:
259
260\begin{verbatim}
261 def perm(l): # error: first line indented
262 for i in range(len(l)): # error: not indented
263 s = l[:i] + l[i+1:]
264 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
265 for x in p:
266 r.append(l[i:i+1] + x)
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000267 return r # error: inconsistent dedent
Guido van Rossum7b632a61992-01-16 17:49:21 +0000268\end{verbatim}
269
270(Actually, the first three errors are detected by the parser; only the
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000271last error is found by the lexical analyzer --- the indentation of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000272\verb\return r\ does not match a level popped off the stack.)
273
Guido van Rossumf2612d11991-11-21 13:53:03 +0000274\section{Other tokens}
275
276Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
277exist: identifiers, keywords, literals, operators, and delimiters.
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000278Spaces and tabs are not tokens, but serve to delimit tokens. Where
279ambiguity exists, a token comprises the longest possible string that
280forms a legal token, when read from left to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000281
Guido van Rossumf2612d11991-11-21 13:53:03 +0000282\section{Identifiers}
283
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000284Identifiers (also referred to as names) are described by the following
285lexical definitions:
286\index{identifier}
287\index{name}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000288
289\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000290identifier: (letter|"_") (letter|digit|"_")*
Guido van Rossumf2612d11991-11-21 13:53:03 +0000291letter: lowercase | uppercase
Guido van Rossum743d1e71992-01-07 16:43:53 +0000292lowercase: "a"..."z"
293uppercase: "A"..."Z"
294digit: "0"..."9"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000295\end{verbatim}
296
Guido van Rossum670e5a01992-01-17 14:03:20 +0000297Identifiers are unlimited in length. Case is significant.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000298
Guido van Rossum670e5a01992-01-17 14:03:20 +0000299\subsection{Keywords}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000300
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000301The following identifiers are used as reserved words, or {\em
Guido van Rossum7b632a61992-01-16 17:49:21 +0000302keywords} of the language, and cannot be used as ordinary
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000303identifiers. They must be spelled exactly as written here:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000304\index{keyword}
305\index{reserved word}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000306
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000307\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000308and del for in print
309break elif from is raise
310class else global not return
311continue except if or try
312def finally import pass while
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000313\end{verbatim}
314
Guido van Rossum743d1e71992-01-07 16:43:53 +0000315% # This Python program sorts and formats the above table
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000316% import string
317% l = []
318% try:
319% while 1:
320% l = l + string.split(raw_input())
321% except EOFError:
322% pass
323% l.sort()
324% for i in range((len(l)+4)/5):
325% for j in range(i, len(l), 5):
326% print string.ljust(l[j], 10),
327% print
Guido van Rossumf2612d11991-11-21 13:53:03 +0000328
329\section{Literals}
330
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000331Literals are notations for constant values of some built-in types.
332\index{literal}
333\index{constant}
334
Guido van Rossumf2612d11991-11-21 13:53:03 +0000335\subsection{String literals}
336
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000337String literals are described by the following lexical definitions:
338\index{string literal}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000339
340\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000341stringliteral: "'" stringitem* "'"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000342stringitem: stringchar | escapeseq
Guido van Rossum743d1e71992-01-07 16:43:53 +0000343stringchar: <any ASCII character except newline or "\" or "'">
344escapeseq: "'" <any ASCII character except newline>
Guido van Rossumf2612d11991-11-21 13:53:03 +0000345\end{verbatim}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000346\index{ASCII}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000347
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000348String literals cannot span physical line boundaries. Escape
349sequences in strings are actually interpreted according to rules
350simular to those used by Standard C. The recognized escape sequences
351are:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000352\index{physical line}
353\index{escape sequence}
354\index{Standard C}
355\index{C}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000356
357\begin{center}
358\begin{tabular}{|l|l|}
359\hline
360\verb/\\/ & Backslash (\verb/\/) \\
361\verb/\'/ & Single quote (\verb/'/) \\
362\verb/\a/ & ASCII Bell (BEL) \\
363\verb/\b/ & ASCII Backspace (BS) \\
Guido van Rossum7b632a61992-01-16 17:49:21 +0000364%\verb/\E/ & ASCII Escape (ESC) \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000365\verb/\f/ & ASCII Formfeed (FF) \\
366\verb/\n/ & ASCII Linefeed (LF) \\
367\verb/\r/ & ASCII Carriage Return (CR) \\
368\verb/\t/ & ASCII Horizontal Tab (TAB) \\
369\verb/\v/ & ASCII Vertical Tab (VT) \\
370\verb/\/{\em ooo} & ASCII character with octal value {\em ooo} \\
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000371\verb/\x/{\em xx...} & ASCII character with hex value {\em xx...} \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000372\hline
373\end{tabular}
374\end{center}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000375\index{ASCII}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000376
Guido van Rossum7b632a61992-01-16 17:49:21 +0000377In strict compatibility with in Standard C, up to three octal digits are
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000378accepted, but an unlimited number of hex digits is taken to be part of
379the hex escape (and then the lower 8 bits of the resulting hex number
Guido van Rossum7b632a61992-01-16 17:49:21 +0000380are used in all current implementations...).
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000381
Guido van Rossum7b632a61992-01-16 17:49:21 +0000382All unrecognized escape sequences are left in the string unchanged,
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000383i.e., {\em the backslash is left in the string.} (This behavior is
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000384useful when debugging: if an escape sequence is mistyped, the
Guido van Rossum743d1e71992-01-07 16:43:53 +0000385resulting output is more easily recognized as broken. It also helps a
386great deal for string literals used as regular expressions or
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000387otherwise passed to other modules that do their own escape handling.)
388\index{unrecognized escape sequence}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000389
390\subsection{Numeric literals}
391
Guido van Rossum670e5a01992-01-17 14:03:20 +0000392There are three types of numeric literals: plain integers, long
393integers, and floating point numbers.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000394\index{number}
395\index{numeric literal}
396\index{integer literal}
397\index{plain integer literal}
398\index{long integer literal}
399\index{floating point literal}
400\index{hexadecimal literal}
401\index{octal literal}
402\index{decimal literal}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000403
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000404Integer and long integer literals are described by the following
405lexical definitions:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000406
407\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000408longinteger: integer ("l"|"L")
Guido van Rossumf2612d11991-11-21 13:53:03 +0000409integer: decimalinteger | octinteger | hexinteger
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000410decimalinteger: nonzerodigit digit* | "0"
411octinteger: "0" octdigit+
412hexinteger: "0" ("x"|"X") hexdigit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000413
Guido van Rossum743d1e71992-01-07 16:43:53 +0000414nonzerodigit: "1"..."9"
415octdigit: "0"..."7"
416hexdigit: digit|"a"..."f"|"A"..."F"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000417\end{verbatim}
418
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000419Although both lower case `l' and upper case `L' are allowed as suffix
Guido van Rossum670e5a01992-01-17 14:03:20 +0000420for long integers, it is strongly recommended to always use `L', since
421the letter `l' looks too much like the digit `1'.
422
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000423Plain integer decimal literals must be at most $2^{31} - 1$ (i.e., the
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000424largest positive integer, assuming 32-bit arithmetic). Plain octal and
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000425hexadecimal literals may be as large as $2^{32} - 1$, but values
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000426larger than $2^{31} - 1$ are converted to a negative value by
427subtracting $2^{32}$. There is no limit for long integer literals.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000428
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000429Some examples of plain and long integer literals:
Guido van Rossum670e5a01992-01-17 14:03:20 +0000430
431\begin{verbatim}
4327 2147483647 0177 0x80000000
Guido van Rossumb5e1c181992-03-06 10:52:59 +00004333L 79228162514264337593543950336L 0377L 0x100000000L
Guido van Rossum670e5a01992-01-17 14:03:20 +0000434\end{verbatim}
435
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000436Floating point literals are described by the following lexical
437definitions:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000438
439\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000440floatnumber: pointfloat | exponentfloat
441pointfloat: [intpart] fraction | intpart "."
442exponentfloat: (intpart | pointfloat) exponent
Guido van Rossumf2612d11991-11-21 13:53:03 +0000443intpart: digit+
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000444fraction: "." digit+
445exponent: ("e"|"E") ["+"|"-"] digit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000446\end{verbatim}
447
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000448The allowed range of floating point literals is
449implementation-dependent.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000450
451Some examples of floating point literals:
Guido van Rossum7b632a61992-01-16 17:49:21 +0000452
453\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00004543.14 10. .001 1e100 3.14e-10
Guido van Rossum7b632a61992-01-16 17:49:21 +0000455\end{verbatim}
456
Guido van Rossum670e5a01992-01-17 14:03:20 +0000457Note that numeric literals do not include a sign; a phrase like
458\verb\-1\ is actually an expression composed of the operator
Guido van Rossum7b632a61992-01-16 17:49:21 +0000459\verb\-\ and the literal \verb\1\.
460
Guido van Rossumf2612d11991-11-21 13:53:03 +0000461\section{Operators}
462
463The following tokens are operators:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000464\index{operators}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000465
466\begin{verbatim}
467+ - * / %
468<< >> & | ^ ~
Guido van Rossum743d1e71992-01-07 16:43:53 +0000469< == > <= <> != >=
Guido van Rossumf2612d11991-11-21 13:53:03 +0000470\end{verbatim}
471
Guido van Rossum743d1e71992-01-07 16:43:53 +0000472The comparison operators \verb\<>\ and \verb\!=\ are alternate
473spellings of the same operator.
474
Guido van Rossumf2612d11991-11-21 13:53:03 +0000475\section{Delimiters}
476
Guido van Rossum743d1e71992-01-07 16:43:53 +0000477The following tokens serve as delimiters or otherwise have a special
478meaning:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000479\index{delimiters}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000480
481\begin{verbatim}
482( ) [ ] { }
Guido van Rossum743d1e71992-01-07 16:43:53 +0000483; , : . ` =
Guido van Rossumf2612d11991-11-21 13:53:03 +0000484\end{verbatim}
485
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000486The following printing ASCII characters are not used in Python. Their
487occurrence outside string literals and comments is an unconditional
488error:
489\index{ASCII}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000490
491\begin{verbatim}
492! @ $ " ?
493\end{verbatim}
494
Guido van Rossum7b632a61992-01-16 17:49:21 +0000495They may be used by future versions of the language though!
496
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000497\chapter{Data model}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000498
Guido van Rossum743d1e71992-01-07 16:43:53 +0000499\section{Objects, values and types}
500
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000501{\em Objects} are Python's abstraction for data. All data in a Python
502program is represented by objects or by relations between objects.
503(In a sense, and in conformance to Von Neumann's model of a
504``stored program computer'', code is also represented by objects.)
505\index{object}
506\index{data}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000507
508Every object has an identity, a type and a value. An object's {\em
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000509identity} never changes once it has been created; you may think of it
510as the object's address in memory. An object's {\em type} is also
511unchangeable. It determines the operations that an object supports
512(e.g., ``does it have a length?'') and also defines the possible
513values for objects of that type. The {\em value} of some objects can
514change. Objects whose value can change are said to be {\em mutable};
515objects whose value is unchangeable once they are created are called
516{\em immutable}. The type determines an object's (im)mutability.
517\index{identity of an object}
518\index{value of an object}
519\index{type of an object}
520\index{mutable object}
521\index{immutable object}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000522
523Objects are never explicitly destroyed; however, when they become
Guido van Rossum670e5a01992-01-17 14:03:20 +0000524unreachable they may be garbage-collected. An implementation is
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000525allowed to delay garbage collection or omit it altogether --- it is a
Guido van Rossum670e5a01992-01-17 14:03:20 +0000526matter of implementation quality how garbage collection is
527implemented, as long as no objects are collected that are still
528reachable. (Implementation note: the current implementation uses a
Guido van Rossum743d1e71992-01-07 16:43:53 +0000529reference-counting scheme which collects most objects as soon as they
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000530become unreachable, but never collects garbage containing circular
Guido van Rossum743d1e71992-01-07 16:43:53 +0000531references.)
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000532\index{garbage collection}
533\index{reference counting}
534\index{unreachable object}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000535
Guido van Rossum670e5a01992-01-17 14:03:20 +0000536Note that the use of the implementation's tracing or debugging
537facilities may keep objects alive that would normally be collectable.
538
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000539Some objects contain references to ``external'' resources such as open
540files or windows. It is understood that these resources are freed
541when the object is garbage-collected, but since garbage collection is
542not guaranteed to happen, such objects also provide an explicit way to
543release the external resource, usually a \verb\close\ method.
544Programs are strongly recommended to always explicitly close such
545objects.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000546
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000547Some objects contain references to other objects; these are called
548{\em containers}. Examples of containers are tuples, lists and
549dictionaries. The references are part of a container's value. In
550most cases, when we talk about the value of a container, we imply the
551values, not the identities of the contained objects; however, when we
552talk about the (im)mutability of a container, only the identities of
553the immediately contained objects are implied. (So, if an immutable
554container contains a reference to a mutable object, its value changes
555if that mutable object is changed.)
556\index{container}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000557
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000558Types affect almost all aspects of objects' lives. Even the meaning
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000559of object identity is affected in some sense: for immutable types,
560operations that compute new values may actually return a reference to
561any existing object with the same type and value, while for mutable
562objects this is not allowed. E.g., after
Guido van Rossum743d1e71992-01-07 16:43:53 +0000563
564\begin{verbatim}
565a = 1; b = 1; c = []; d = []
566\end{verbatim}
567
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000568\verb\a\ and \verb\b\ may or may not refer to the same object with the
569value one, depending on the implementation, but \verb\c\ and \verb\d\
570are guaranteed to refer to two different, unique, newly created empty
571lists.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000572
Guido van Rossum60279da1992-04-02 10:24:59 +0000573\section{The standard type hierarchy} \label{types}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000574
575Below is a list of the types that are built into Python. Extension
576modules written in C can define additional types. Future versions of
577Python may add types to the type hierarchy (e.g., rational or complex
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000578numbers, efficiently stored arrays of integers, etc.).
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000579\index{type}
580\index{type hierarchy}
581\index{extension module}
582\index{C}
583
584Some of the type descriptions below contain a paragraph listing
585`special attributes'. These are attributes that provide access to the
586implementation and are not intended for general use. Their definition
587may change in the future. There are also some `generic' special
588attributes, not listed with the individual objects: \verb\__methods__\
589is a list of the method names of a built-in object, if it has any;
590\verb\__members__\ is a list of the data attribute names of a built-in
591object, if it has any.
592\index{attribute}
593\index{special attribute}
594\index{generic special attribute}
595\ttindex{__methods__}
596\ttindex{__members__}
597
598\begin{description}
599
600\item[None]
601This type has a single value. There is a single object with this value.
602This object is accessed through the built-in name \verb\None\.
603It is returned from functions that don't explicitly return an object.
604\ttindex{None}
605
606\item[Numbers]
607These are created by numeric literals and returned as results
608by arithmetic operators and arithmetic built-in functions.
609Numeric objects are immutable; once created their value never changes.
610Python numbers are of course strongly related to mathematical numbers,
611but subject to the limitations of numerical representation in computers.
612\index{number}
613
614Python distinguishes between integers and floating point numbers:
615
616\begin{description}
617\item[Integers]
618These represent elements from the mathematical set of whole numbers.
619\index{integer}
620
621There are two types of integers:
622
623\begin{description}
624
625\item[Plain integers]
626These represent numbers in the range $-2^{31}$ through $2^{31}-1$.
627(The range may be larger on machines with a larger natural word
628size, but not smaller.)
629When the result of an operation falls outside this range, the
630exception \verb\OverflowError\ is raised.
631For the purpose of shift and mask operations, integers are assumed to
632have a binary, 2's complement notation using 32 or more bits, and
633hiding no bits from the user (i.e., all $2^{32}$ different bit
634patterns correspond to different values).
635\index{plain integer}
636
637\item[Long integers]
638These represent numbers in an unlimited range, subject to avaiable
639(virtual) memory only. For the purpose of shift and mask operations,
640a binary representation is assumed, and negative numbers are
641represented in a variant of 2's complement which gives the illusion of
642an infinite string of sign bits extending to the left.
643\index{long integer}
644
645\end{description} % Integers
646
647The rules for integer representation are intended to give the most
648meaningful interpretation of shift and mask operations involving
649negative integers and the least surprises when switching between the
650plain and long integer domains. For any operation except left shift,
651if it yields a result in the plain integer domain without causing
652overflow, it will yield the same result in the long integer domain or
653when using mixed operands.
654\index{integer representation}
655
656\item[Floating point numbers]
657These represent machine-level double precision floating point numbers.
658You are at the mercy of the underlying machine architecture and
659C implementation for the accepted range and handling of overflow.
660\index{floating point number}
661\index{C}
662
663\end{description} % Numbers
664
665\item[Sequences]
666These represent finite ordered sets indexed by natural numbers.
667The built-in function \verb\len()\ returns the number of elements
668of a sequence. When this number is $n$, the index set contains
669the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence
670\verb\a\ is selected by \verb\a[i]\.
671\index{seqence}
672\bifuncindex{len}
673\index{index operation}
674\index{item selection}
675\index{subscription}
676
677Sequences also support slicing: \verb\a[i:j]\ selects all elements
678with index $k$ such that $i < k < j$. When used as an expression,
679a slice is a sequence of the same type --- this implies that the
680index set is renumbered so that it starts at 0 again.
681\index{slicing}
682
683Sequences are distinguished according to their mutability:
684
685\begin{description}
686%
687\item[Immutable sequences]
688An object of an immutable sequence type cannot change once it is
689created. (If the object contains references to other objects,
690these other objects may be mutable and may be changed; however
691the collection of objects directly referenced by an immutable object
692cannot change.)
693\index{immutable sequence}
694
695The following types are immutable sequences:
696
697\begin{description}
698
699\item[Strings]
700The elements of a string are characters. There is no separate
701character type; a character is represented by a string of one element.
702Characters represent (at least) 8-bit bytes. The built-in
703functions \verb\chr()\ and \verb\ord()\ convert between characters
704and nonnegative integers representing the byte values.
705Bytes with the values 0-127 represent the corresponding ASCII values.
706The string data type is also used to represent arrays of bytes, e.g.,
707to hold data read from a file.
708\index{string}
709\index{character}
710\index{byte}
711\index{ASCII}
712\bifuncindex{chr}
713\bifuncindex{ord}
714
715(On systems whose native character set is not ASCII, strings may use
716EBCDIC in their internal representation, provided the functions
717\verb\chr()\ and \verb\ord()\ implement a mapping between ASCII and
718EBCDIC, and string comparison preserves the ASCII order.
719Or perhaps someone can propose a better rule?)
720\index{ASCII}
721\index{EBCDIC}
722\index{character set}
723\index{string comparison}
724\bifuncindex{chr}
725\bifuncindex{ord}
726
727\item[Tuples]
728The elements of a tuple are arbitrary Python objects.
729Tuples of two or more elements are formed by comma-separated lists
730of expressions. A tuple of one element (a `singleton') can be formed
731by affixing a comma to an expression (an expression by itself does
732not create a tuple, since parentheses must be usable for grouping of
733expressions). An empty tuple can be formed by enclosing `nothing' in
734parentheses.
735\index{tuple}
736\index{singleton tuple}
737\index{empty tuple}
738
739\end{description} % Immutable sequences
740
741\item[Mutable sequences]
742Mutable sequences can be changed after they are created. The
743subscription and slicing notations can be used as the target of
744assignment and \verb\del\ (delete) statements.
745\index{mutable sequece}
746\index{assignment statement}
747\kwindex{del}
748\index{subscription}
749\index{slicing}
750
751There is currently a single mutable sequence type:
752
753\begin{description}
754
755\item[Lists]
756The elements of a list are arbitrary Python objects. Lists are formed
757by placing a comma-separated list of expressions in square brackets.
758(Note that there are no special cases needed to form lists of length 0
759or 1.)
760\index{list}
761
762\end{description} % Mutable sequences
763
764\end{description} % Sequences
765
766\item[Mapping types]
767These represent finite sets of objects indexed by arbitrary index sets.
768The subscript notation \verb\a[k]\ selects the element indexed
769by \verb\k\ from the mapping \verb\a\; this can be used in
770expressions and as the target of assignments or \verb\del\ statements.
771The built-in function \verb\len()\ returns the number of elements
772in a mapping.
773\bifuncindex{len}
774\index{subscription}
775\index{mapping}
776
777There is currently a single mapping type:
778
779\begin{description}
780
781\item[Dictionaries]
782These represent finite sets of objects indexed by strings.
783Dictionaries are created by the \verb\{...}\ notation (see section
784\ref{dict}). (Implementation note: the strings used for indexing must
785not contain null bytes.)
786\index{dictionary}
787
788\end{description} % Mapping types
789
790\item[Callable types]
791These are the types to which the function call (invocation) operation,
792written as \verb\function(argument, argument, ...)\, can be applied:
793\index{callable type}
794\indexii{function}{call}
795\index{invocation}
796
797\begin{description}
798
799\item[User-defined functions]
800A user-defined function object is created by a function definition
801(see section \ref{function}). It should be called with an argument
802list containing the same number of items as the function's formal
803parameter list.
804\indexii{user-defined}{function}
805\index{function object}
806
807Special read-only attributes: \verb\func_code\ is the code object
808representing the compiled function body, and \verb\func_globals\ is (a
809reference to) the dictionary that holds the function's global
810variables --- it implements the global name space of the module in
811which the function was defined.
812\ttindex{func_code}
813\ttindex{func_globals}
814\indexii{global}{name space}
815
816\item[User-defined methods]
Guido van Rossum60279da1992-04-02 10:24:59 +0000817A user-defined method (a.k.a. {\em object closure}) is a pair of a
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000818class instance object and a user-defined function. It should be
819called with an argument list containing one item less than the number
820of items in the function's formal parameter list. When called, the
821class instance becomes the first argument, and the call arguments are
822shifted one to the right.
823\indexii{object}{closure}
824indexii{user-defined}{method}
825
826Special read-only attributes: \verb\im_self\ is the class instance
827object, \verb\im_func\ is the function object.
828\ttindex{im_func}
829\ttindex{im_self}
830
831\item[Built-in functions]
832A built-in function object is a wrapper around a C function. Examples
833of built-in functions are \verb\len\ and \verb\math.sin\. There
834are no special attributes. The number and type of the arguments are
835determined by the C function.
836\index{C}
837
838\item[Built-in methods]
839This is really a different disguise of a built-in function, this time
840containing an object passed to the C function as an implicit extra
841argument. An example of a built-in method is \verb\list.append\ if
842\verb\list\ is a list object.
843\indexii{built-in}{method}
844
845\item[Classes]
846Class objects are described below. When a class object is called as a
847parameterless function, a new class instance (also described below) is
848created and returned. The class's initialization function is not
849called --- this is the responsibility of the caller. It is illegal to
850call a class object with one or more arguments.
851\index{class}
852
853\end{description}
854
855\item[Modules]
856Modules are imported by the \verb\import\ statement (see section
857\ref{import}). A module object is a container for a module's name
858space, which is a dictionary (the same dictionary as referenced by the
859\verb\func_globals\ attribute of functions defined in the module).
860Module attribute references are translated to lookups in this
861dictionary. A module object does not contain the code object used to
862initialize the module (since it isn't needed once the initialization
863is done).
864\stindex{import}
865\index{module}
866
867Attribute assignment update the module's name space dictionary.
868
869Special read-only attributes: \verb\__dict__\ yields the module's name
870space as a dictionary object; \verb\__name__\ yields the module's name
871as a string object.
872\ttindex{__dict__}
873\ttindex{__name__}
874
875\item[Classes]
876Class objects are created by class definitions (see section
877\ref{class}). A class is a container for a dictionary containing the
878class's name space. Class attribute references are translated to
879lookups in this dictionary. When an attribute name is not found
880there, the attribute search continues in the base classes. The search
881is depth-first, left-to-right in the order of their occurrence in the
882base class list.
883\index{class}
884\index{container}
885\index{dictionary}
886\indexii{class}{attribute}
887
888Class attribute assignments update the class's dictionary, never the
889dictionary of a base class.
890\indexiii{class}{attribute}{assignment}
891
892A class can be called as a parameterless function to yield a class
893instance (see above).
894
895Special read-only attributes: \verb\__dict__\ yields te dictionary
896containing the class's name space; \verb\__bases__\ yields a tuple
897(possibly empty or a singleton) containing the base classes, in the
898order of their occurrence in the base class list.
899\ttindex{__dict__}
900\ttindex{__bases__}
901
902\item[Class instances]
903A class instance is created by calling a class object as a
904parameterless function. A class instance has a dictionary in which
905attribute references are searched. When an attribute is not found
906there, and the instance's class has an attribute by that name, and
907that class attribute is a user-defined function (and in no other
908cases), the instance attribute reference yields a user-defined method
909object (see above) constructed from the instance and the function.
910\indexii{class}{instance}
911\indexii{class instance}{attribute}
912
913Attribute assignments update the instance's dictionary.
914\indexiii{class instance}{attribute}{assignment}
915
916Special read-only attributes: \verb\__dict__\ yields the attribute
917dictionary; \verb\__class__\ yields the instance's class.
918\ttindex{__dict__}
919\ttindex{__class__}
920
921\item[Files]
922A file object represents an open file. (It is a wrapper around a C
923{\tt stdio} file pointer.) File objects are created by the
924\verb\open()\ built-in function, and also by \verb\posix.popen()\ and
925the \verb\makefile\ method of socket objects. \verb\sys.stdin\,
926\verb\sys.stdout\ and \verb\sys.stderr\ are file objects corresponding
927the the interpreter's standard input, output and error streams.
928See the Python Library Reference for methods of file objects and other
929details.
930\index{file}
931\index{C}
932\index{stdio}
933\bifuncindex{open}
934\bifuncindex{popen}
935\bifuncindex{makefile}
936\ttindex{stdin}
937\ttindex{stdout}
938\ttindex{stderr}
939
940\item[Internal types]
941A few types used internally by the interpreter are exposed to the user.
942Their definition may change with future versions of the interpreter,
943but they are mentioned here for completeness.
944\index{internal type}
945
946\begin{description}
947
948\item[Code objects]
949Code objects represent executable code. The difference between a code
950object and a function object is that the function object contains an
951explicit reference to the function's context (the module in which it
952was defined) which a code object contains no context. There is no way
953to execute a bare code object.
954\index{code object}
955
956Special read-only attributes: \verb\co_code\ is a string representing
957the sequence of instructions; \verb\co_consts\ is a list of literals
958used by the code; \verb\co_names\ is a list of names (strings) used by
959the code; \verb\co_filename\ is the filename from which the code was
960compiled. (To find out the line numbers, you would have to decode the
961instructions; the standard library module \verb\dis\ contains an
962example of how to do this.)
963\ttindex{co_code}
964\ttindex{co_consts}
965\ttindex{co_names}
966\ttindex{co_filename}
967
968\item[Frame objects]
969Frame objects represent execution frames. They may occur in traceback
970objects (see below).
971\index{frame object}
972
973Special read-only attributes: \verb\f_back\ is to the previous
974stack frame (towards the caller), or \verb\None\ if this is the bottom
975stack frame; \verb\f_code\ is the code object being executed in this
976frame; \verb\f_globals\ is the dictionary used to look up global
977variables; \verb\f_locals\ is used for local variables;
978\verb\f_lineno\ gives the line number and \verb\f_lasti\ gives the
979precise instruction (this is an index into the instruction string of
980the code object).
981\ttindex{f_back}
982\ttindex{f_code}
983\ttindex{f_globals}
984\ttindex{f_locals}
985\ttindex{f_lineno}
986\ttindex{f_lasti}
987
988\item[Traceback objects]
989Traceback objects represent a stack trace of an exception. A
990traceback object is created when an exception occurs. When the search
991for an exception handler unwinds the execution stack, at each unwound
992level a traceback object is inserted in front of the current
993traceback. When an exception handler is entered, the stack trace is
994made available to the program as \verb\sys.exc_traceback\. When the
995program contains no suitable handler, the stack trace is written
996(nicely formatted) to the standard error stream; if the interpreter is
997interactive, it is also made available to the user as
998\verb\sys.last_traceback\.
999\index{traceback object}
1000\indexii{stack}{trace}
1001\index{exception handler}
1002\index{execution stack}
1003\ttindex{exc_traceback}
1004\ttindex{last_traceback}
1005
1006Special read-only attributes: \verb\tb_next\ is the next level in the
1007stack trace (towards the frame where the exception occurred), or
1008\verb\None\ if there is no next level; \verb\tb_frame\ points to the
1009execution frame of the current level; \verb\tb_lineno\ gives the line
1010number where the exception occurred; \verb\tb_lasti\ indicates the
1011precise instruction. The line number and last instruction in the
1012traceback may differ from the line number of its frame object if the
1013exception occurred in a \verb\try\ statement with no matching
1014\verb\except\ clause or with a \verb\finally\ clause.
1015\ttindex{tb_next}
1016\ttindex{tb_frame}
1017\ttindex{tb_lineno}
1018\ttindex{tb_lasti}
1019\stindex{try}
1020
1021\end{description} % Internal types
1022
1023\end{description} % Types
1024
1025\chapter{Execution model}
1026
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001027\section{Code blocks, execution frames, and name spaces}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001028
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001029A {\em code block} is a piece of Python program text that can be
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001030executed as a unit, such as a module, a class definition or a function
1031body. Some code blocks (like modules) are executed only once, others
1032(like function bodies) may be executed many times. Code block may
1033textually contain other code blocks. Code blocks may invoke other
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001034code blocks (that may or may not be textually contained in them) as
1035part of their execution, e.g., by invoking (calling) a function.
1036\index{code block}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001037
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001038The following are code blocks: A module is a code block. A function
1039body is a code block. A class definition is a code block. Each
1040command typed interactively is a separate code block; a script file is
1041a code block. The string argument passed to the built-in functions
1042\verb\eval\ and \verb\exec\ are code blocks. And finally, the
1043expression read and evaluated by the built-in function \verb\input\ is
1044a code block.
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001045
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001046A code block is executed in an execution frame. An {\em execution
1047frame} contains some administrative information (used for debugging),
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001048determines where and how execution continues after the code block's
1049execution has completed, and (perhaps most importantly) defines two
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001050name spaces, the local and the global name space, that affect
1051execution of the code block.
1052\index{execution frame}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001053
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001054A {\em name space} is a mapping from names (identifiers) to objects.
1055A particular name space may be referenced by more than one execution
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001056frame, and from other places as well. Adding a name to a name space
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001057is called {\em binding} a name (to an object); changing the mapping of
1058a name is called {\em rebinding}; removing a name is {\em unbinding}.
1059Name spaces are functionally equivalent to dictionaries.
1060\index{name space}
1061\indexii{binding}{name}
1062\indexii{rebinding}{name}
1063\indexii{unbinding}{name}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001064
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001065The {\em local name space} of an execution frame determines the default
1066place where names are defined and searched. The {\em global name
1067space} determines the place where names listed in \verb\global\
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001068statements are defined and searched, and where names that are not
1069explicitly bound in the current code block are searched.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001070\indexii{local}{name space}
1071\indexii{global}{name space}
1072\stindex{global}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001073
1074Whether a name is local or global in a code block is determined by
1075static inspection of the source text for the code block: in the
1076absence of \verb\global\ statements, a name that is bound anywhere in
1077the code block is local in the entire code block; all other names are
1078considered global. The \verb\global\ statement forces global
1079interpretation of selected names throughout the code block. The
1080following constructs bind names: formal parameters, \verb\import\
1081statements, class and function definitions (these bind the class or
1082function name), and targets that are identifiers if occurring in an
1083assignment, \verb\for\ loop header, or \verb\except\ clause header.
1084(A target occurring in a \verb\del\ statement does not bind a name.)
1085
1086When a global name is not found in the global name space, it is
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001087searched in the list of ``built-in'' names (which is actually the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001088global name space of the module \verb\builtin\). When a name is not
1089found at all, the \verb\NameError\ exception is raised.
1090
1091The following table lists the meaning of the local and global name
1092space for various types of code blocks. The name space for a
1093particular module is automatically created when the module is first
1094referenced.
1095
1096\begin{center}
1097\begin{tabular}{|l|l|l|l|}
1098\hline
1099Code block type & Global name space & Local name space & Notes \\
1100\hline
1101Module & n.s. for this module & same as global & \\
1102Script & n.s. for \verb\__main__\ & same as global & \\
1103Interactive command & n.s. for \verb\__main__\ & same as global & \\
1104Class definition & global n.s. of containing block & new n.s. & \\
1105Function body & global n.s. of containing block & new n.s. & \\
1106String passed to \verb\exec\ or \verb\eval\
1107 & global n.s. of caller & local n.s. of caller & (1) \\
1108File read by \verb\execfile\
1109 & global n.s. of caller & local n.s. of caller & (1) \\
1110Expression read by \verb\input\
1111 & global n.s. of caller & local n.s. of caller & \\
1112\hline
1113\end{tabular}
1114\end{center}
1115
1116Notes:
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001117
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001118\begin{description}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001119
1120\item[n.s.] means {\em name space}
1121
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001122\item[(1)] The global and local name space for these functions can be
1123overridden with optional extra arguments.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001124
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001125\end{description}
1126
1127\section{Exceptions}
1128
1129Exceptions are a means of breaking out of the normal flow of control
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001130of a code block in order to handle errors or other exceptional
1131conditions. An exception is {\em raised} at the point where the error
1132is detected; it may be {\em handled} by the surrounding code block or
1133by any code block that directly or indirectly invoked the code block
1134where the error occurred.
1135\index{exception}
1136\index{raise an exception}
1137\index{handle an exception}
1138\index{exception handler}
1139\index{errors}
1140\index{error handling}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001141
1142The Python interpreter raises an exception when it detects an run-time
1143error (such as division by zero). A Python program can also
1144explicitly raise an exception with the \verb\raise\ statement.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001145Exception handlers are specified with the \verb\try...except\
1146statement.
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001147
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001148Python uses the ``termination'' model of error handling: an exception
1149handler can find out what happened and continue execution at an outer
1150level, but it cannot repair the cause of the error and retry the
1151failing operation (except by re-entering the the offending piece of
1152code from the top).
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001153
1154When an exception is not handled at all, the interpreter terminates
1155execution of the program, or returns to its interactive main loop.
1156
1157Exceptions are identified by string objects. Two different string
1158objects with the same value identify different exceptions.
1159
1160When an exception is raised, an object (maybe \verb\None\) is passed
1161as the exception's ``parameter''; this object does not affect the
1162selection of an exception handler, but is passed to the selected
1163exception handler as additional information.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001164
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001165See also the description of the \verb\try\ and \verb\raise\
1166statements.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001167
Guido van Rossumf2612d11991-11-21 13:53:03 +00001168\chapter{Expressions and conditions}
1169
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001170In this and the following chapters, extended BNF notation will be used
1171to describe syntax, not lexical analysis.
1172\index{BNF}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001173
1174This chapter explains the meaning of the elements of expressions and
1175conditions. Conditions are a superset of expressions, and a condition
Guido van Rossum670e5a01992-01-17 14:03:20 +00001176may be used wherever an expression is required by enclosing it in
1177parentheses. The only places where expressions are used in the syntax
1178instead of conditions is in expression statements and on the
1179right-hand side of assignments; this catches some nasty bugs like
1180accedentally writing \verb\x == 1\ instead of \verb\x = 1\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001181
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001182The comma plays several roles in Python's syntax. It is usually an
Guido van Rossum743d1e71992-01-07 16:43:53 +00001183operator with a lower precedence than all others, but occasionally
Guido van Rossum670e5a01992-01-17 14:03:20 +00001184serves other purposes as well; e.g., it separates function arguments,
1185is used in list and dictionary constructors, and has special semantics
1186in \verb\print\ statements.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001187
1188When (one alternative of) a syntax rule has the form
1189
1190\begin{verbatim}
1191name: othername
1192\end{verbatim}
1193
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001194and no semantics are given, the semantics of this form of \verb\name\
1195are the same as for \verb\othername\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001196
1197\section{Arithmetic conversions}
1198
1199When a description of an arithmetic operator below uses the phrase
1200``the numeric arguments are converted to a common type'',
1201this both means that if either argument is not a number, a
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001202\verb\TypeError\ exception is raised, and that otherwise
Guido van Rossumf2612d11991-11-21 13:53:03 +00001203the following conversions are applied:
1204
1205\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001206\item first, if either argument is a floating point number,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001207 the other is converted to floating point;
1208\item else, if either argument is a long integer,
1209 the other is converted to long integer;
Guido van Rossum670e5a01992-01-17 14:03:20 +00001210\item otherwise, both must be plain integers and no conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +00001211 is necessary.
1212\end{itemize}
1213
Guido van Rossumf2612d11991-11-21 13:53:03 +00001214\section{Atoms}
1215
Guido van Rossum670e5a01992-01-17 14:03:20 +00001216Atoms are the most basic elements of expressions. Forms enclosed in
1217reverse quotes or in parentheses, brackets or braces are also
1218categorized syntactically as atoms. The syntax for atoms is:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001219
1220\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001221atom: identifier | literal | enclosure
1222enclosure: parenth_form | list_display | dict_display | string_conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +00001223\end{verbatim}
1224
1225\subsection{Identifiers (Names)}
1226
1227An identifier occurring as an atom is a reference to a local, global
Guido van Rossum670e5a01992-01-17 14:03:20 +00001228or built-in name binding. If a name can be assigned to anywhere in a
1229code block, and is not mentioned in a \verb\global\ statement in that
1230code block, it refers to a local name throughout that code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001231Otherwise, it refers to a global name if one exists, else to a
1232built-in name.
1233
Guido van Rossum670e5a01992-01-17 14:03:20 +00001234When the name is bound to an object, evaluation of the atom yields
1235that object. When a name is not bound, an attempt to evaluate it
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001236raises a \verb\NameError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001237
1238\subsection{Literals}
1239
Guido van Rossum670e5a01992-01-17 14:03:20 +00001240Python knows string and numeric literals:
1241
1242\begin{verbatim}
1243literal: stringliteral | integer | longinteger | floatnumber
1244\end{verbatim}
1245
Guido van Rossumf2612d11991-11-21 13:53:03 +00001246Evaluation of a literal yields an object of the given type
1247(string, integer, long integer, floating point number)
1248with the given value.
1249The value may be approximated in the case of floating point literals.
1250
Guido van Rossum670e5a01992-01-17 14:03:20 +00001251All literals correspond to immutable data types, and hence the
1252object's identity is less important than its value. Multiple
1253evaluations of literals with the same value (either the same
1254occurrence in the program text or a different occurrence) may obtain
1255the same object or a different object with the same value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001256
1257(In the original implementation, all literals in the same code block
1258with the same type and value yield the same object.)
1259
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001260\subsection{Parenthesized forms}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001261
Guido van Rossum670e5a01992-01-17 14:03:20 +00001262A parenthesized form is an optional condition list enclosed in
1263parentheses:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001264
Guido van Rossum670e5a01992-01-17 14:03:20 +00001265\begin{verbatim}
1266parenth_form: "(" [condition_list] ")"
1267\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001268
Guido van Rossum670e5a01992-01-17 14:03:20 +00001269A parenthesized condition list yields whatever that condition list
1270yields.
1271
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001272An empty pair of parentheses yields an empty tuple object. Since
1273tuples are immutable, the rules for literals apply here.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001274
1275(Note that tuples are not formed by the parentheses, but rather by use
1276of the comma operator. The exception is the empty tuple, for which
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001277parentheses {\em are} required --- allowing unparenthesized ``nothing''
Guido van Rossum670e5a01992-01-17 14:03:20 +00001278in expressions would causes ambiguities and allow common typos to
1279pass uncaught.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001280
1281\subsection{List displays}
1282
Guido van Rossum670e5a01992-01-17 14:03:20 +00001283A list display is a possibly empty series of conditions enclosed in
1284square brackets:
1285
1286\begin{verbatim}
1287list_display: "[" [condition_list] "]"
1288\end{verbatim}
1289
Guido van Rossumf2612d11991-11-21 13:53:03 +00001290A list display yields a new list object.
1291
1292If it has no condition list, the list object has no items.
1293Otherwise, the elements of the condition list are evaluated
1294from left to right and inserted in the list object in that order.
1295
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001296\subsection{Dictionary displays} \label{dict}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001297
Guido van Rossum670e5a01992-01-17 14:03:20 +00001298A dictionary display is a possibly empty series of key/datum pairs
1299enclosed in curly braces:
1300
1301\begin{verbatim}
1302dict_display: "{" [key_datum_list] "}"
1303key_datum_list: [key_datum ("," key_datum)* [","]
1304key_datum: condition ":" condition
1305\end{verbatim}
1306
Guido van Rossumf2612d11991-11-21 13:53:03 +00001307A dictionary display yields a new dictionary object.
1308
Guido van Rossum670e5a01992-01-17 14:03:20 +00001309The key/datum pairs are evaluated from left to right to define the
1310entries of the dictionary: each key object is used as a key into the
1311dictionary to store the corresponding datum.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001312
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001313Keys must be strings, otherwise a \verb\TypeError\ exception is raised.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001314Clashes between duplicate keys are not detected; the last datum
1315(textually rightmost in the display) stored for a given key value
1316prevails.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001317
1318\subsection{String conversions}
1319
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001320A string conversion is a condition list enclosed in reverse (or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001321backward) quotes:
1322
1323\begin{verbatim}
1324string_conversion: "`" condition_list "`"
1325\end{verbatim}
1326
Guido van Rossumf2612d11991-11-21 13:53:03 +00001327A string conversion evaluates the contained condition list and converts the
1328resulting object into a string according to rules specific to its type.
1329
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001330If the object is a string, a number, \verb\None\, or a tuple, list or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001331dictionary containing only objects whose type is one of these, the
1332resulting string is a valid Python expression which can be passed to
1333the built-in function \verb\eval()\ to yield an expression with the
Guido van Rossumf2612d11991-11-21 13:53:03 +00001334same value (or an approximation, if floating point numbers are
1335involved).
1336
1337(In particular, converting a string adds quotes around it and converts
1338``funny'' characters to escape sequences that are safe to print.)
1339
Guido van Rossum670e5a01992-01-17 14:03:20 +00001340It is illegal to attempt to convert recursive objects (e.g., lists or
1341dictionaries that contain a reference to themselves, directly or
1342indirectly.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001343
Guido van Rossum60279da1992-04-02 10:24:59 +00001344\section{Primaries} \label{primaries}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001345
1346Primaries represent the most tightly bound operations of the language.
1347Their syntax is:
1348
1349\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001350primary: atom | attributeref | subscription | slicing | call
Guido van Rossumf2612d11991-11-21 13:53:03 +00001351\end{verbatim}
1352
1353\subsection{Attribute references}
1354
Guido van Rossum670e5a01992-01-17 14:03:20 +00001355An attribute reference is a primary followed by a period and a name:
1356
1357\begin{verbatim}
1358attributeref: primary "." identifier
1359\end{verbatim}
1360
1361The primary must evaluate to an object of a type that supports
1362attribute references, e.g., a module or a list. This object is then
1363asked to produce the attribute whose name is the identifier. If this
1364attribute is not available, the exception \verb\AttributeError\ is
1365raised. Otherwise, the type and value of the object produced is
1366determined by the object. Multiple evaluations of the same attribute
1367reference may yield different objects.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001368
1369\subsection{Subscriptions}
1370
Guido van Rossum670e5a01992-01-17 14:03:20 +00001371A subscription selects an item of a sequence or mapping object:
1372
1373\begin{verbatim}
1374subscription: primary "[" condition "]"
1375\end{verbatim}
1376
1377The primary must evaluate to an object of a sequence or mapping type.
1378
1379If it is a mapping, the condition must evaluate to an object whose
1380value is one of the keys of the mapping, and the subscription selects
1381the value in the mapping that corresponds to that key.
1382
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001383If it is a sequence, the condition must evaluate to a plain integer.
1384If this value is negative, the length of the sequence is added to it
1385(so that, e.g., \verb\x[-1]\ selects the last item of \verb\x\.)
1386The resulting value must be a nonnegative integer smaller than the
1387number of items in the sequence, and the subscription selects the item
1388whose index is that value (counting from zero).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001389
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001390A string's items are characters. A character is not a separate data
Guido van Rossum670e5a01992-01-17 14:03:20 +00001391type but a string of exactly one character.
1392
Guido van Rossumf2612d11991-11-21 13:53:03 +00001393\subsection{Slicings}
1394
Guido van Rossum670e5a01992-01-17 14:03:20 +00001395A slicing selects a range of items in a sequence object:
1396
1397\begin{verbatim}
1398slicing: primary "[" [condition] ":" [condition] "]"
1399\end{verbatim}
1400
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001401The primary must evaluate to a sequence object. The lower and upper
1402bound expressions, if present, must evaluate to plain integers;
1403defaults are zero and the sequence's length, respectively. If either
1404bound is negative, the sequence's length is added to it. The slicing
1405now selects all items with index $k$ such that $i <= k < j$ where $i$
1406and $j$ are the specified lower and upper bounds. This may be an
1407empty sequence. It is not an error if $i$ or $j$ lie outside the
1408range of valid indexes (such items don't exist so they aren't
1409selected).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001410
1411\subsection{Calls}
1412
1413A call calls a function with a possibly empty series of arguments:
1414
1415\begin{verbatim}
1416call: primary "(" [condition_list] ")"
1417\end{verbatim}
1418
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001419The primary must evaluate to a callable object (user-defined
1420functions, built-in functions, methods of built-in objects, class
1421objects, and methods of class instances are callable). If it is a
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001422class, the argument list must be empty; otherwise, the arguments are
1423evaluated.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001424
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001425A call always returns some value, possibly \verb\None\, unless it
1426raises an exception. How this value is computed depends on the type
1427of the callable object. If it is:
1428
1429\begin{description}
1430
1431\item[a user-defined function:] the code block for the function is
1432executed, passing it the argument list. The first thing the code
1433block will do is bind the formal parameters to the arguments. When
1434the code block executes a \verb\return\ statement, this specifies the
1435return value of the function call.
1436
1437\item[a built-in function or method:] the result is up to the
1438interpreter; see the library reference manual for the descriptions of
1439built-in functions and methods.
1440
1441\item[a class object:] a new instance of that class is returned.
1442
1443\item[a class instance method:] the corresponding user-defined
1444function is called, with an argument list that is one longer than the
1445argument list of the call: the instance becomes the first argument.
1446
1447\end{description}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001448
Guido van Rossum60279da1992-04-02 10:24:59 +00001449\section{Unary arithmetic operations}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001450
Guido van Rossum60279da1992-04-02 10:24:59 +00001451All unary arithmetic (and bit-wise) operations have the same priority:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001452
1453\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001454u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001455\end{verbatim}
1456
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001457The unary \verb\"-"\ operator yields the negative of its
1458numeric argument.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001459
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001460The unary \verb\"+"\ operator yields its numeric argument unchanged.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001461
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001462The unary \verb\"~"\ operator yields the bit-wise negation of its
1463plain or long integer argument. The bit-wise negation negation of
1464\verb\x\ is defined as \verb\-(x+1)\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001465
1466In all three cases, if the argument does not have the proper type,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001467a \verb\TypeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001468
Guido van Rossum60279da1992-04-02 10:24:59 +00001469\section{Binary arithmetic operations}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001470
Guido van Rossum60279da1992-04-02 10:24:59 +00001471The binary arithmetic operations have the conventional priority
1472levels. Note that some of these operations also apply to certain
1473non-numeric types. There is no ``power'' operator, so there are only
1474two levels, one for multiplicative operators and one for additive
1475operators:
1476
Guido van Rossumf2612d11991-11-21 13:53:03 +00001477\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001478m_expr: u_expr | m_expr "*" u_expr | m_expr "/" u_expr | m_expr "%" u_expr
1479a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001480\end{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001481
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001482The \verb\"*"\ (multiplication) operator yields the product of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001483arguments. The arguments must either both be numbers, or one argument
1484must be a plain integer and the other must be a sequence. In the
1485former case, the numbers are converted to a common type and then
1486multiplied together. In the latter case, sequence repetition is
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001487performed; a negative repetition factor yields an empty sequence.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001488
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001489The \verb\"/"\ (division) operator yields the quotient of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001490arguments. The numeric arguments are first converted to a common
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001491type. Plain or long integer division yields an integer of the same
1492type; the result is that of mathematical division with the `floor'
1493function applied to the result. Division by zero raises the
1494\verb\ZeroDivisionError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001495
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001496The \verb\"%"\ (modulo) operator yields the remainder from the
Guido van Rossum670e5a01992-01-17 14:03:20 +00001497division of the first argument by the second. The numeric arguments
Guido van Rossum60279da1992-04-02 10:24:59 +00001498are first converted to a common type. A zero right argument raises
1499the \verb\ZeroDivisionError\ exception. The arguments may be floating
1500point numbers, e.g., \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo
1501operator always yields a result with the same sign as its second
1502operand (or zero); the absolute value of the result is strictly
1503smaller than the second operand.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001504
1505The integer division and modulo operators are connected by the
Guido van Rossum60279da1992-04-02 10:24:59 +00001506following identity: \verb\x == (x/y)*y + (x%y)\. Integer division and
1507modulo are also connected with the built-in function \verb\divmod()\:
1508\verb\divmod(x, y) == (x/y, x%y)\. These identities don't hold for
1509floating point numbers; there a similar identity holds where
1510\verb\x/y\ is replaced by \verb\floor(x/y)\).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001511
Guido van Rossum60279da1992-04-02 10:24:59 +00001512The \verb\"+"\ (addition) operator yields the sum of its arguments.
1513The arguments must either both be numbers, or both sequences of the
1514same type. In the former case, the numbers are converted to a common
1515type and then added together. In the latter case, the sequences are
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001516concatenated.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001517
Guido van Rossum60279da1992-04-02 10:24:59 +00001518The \verb\"-"\ (subtraction) operator yields the difference of its
1519arguments. The numeric arguments are first converted to a common
1520type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001521
Guido van Rossum60279da1992-04-02 10:24:59 +00001522\section{Shifting operations}
1523
1524The shifting operations have lower priority than the arithmetic
1525operations:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001526
1527\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001528shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001529\end{verbatim}
1530
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001531These operators accept plain or long integers as arguments. The
1532arguments are converted to a common type. They shift the first
1533argument to the left or right by the number of bits given by the
1534second argument.
1535
1536A right shift by $n$ bits is defined as division by $2^n$. A left
Guido van Rossum60279da1992-04-02 10:24:59 +00001537shift by $n$ bits is defined as multiplication with $2^n$; for plain
1538integers there is no overflow check so this drops bits and flip the
1539sign if the result is not less than $2^{31}$ in absolute value.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001540
1541Negative shift counts raise a \verb\ValueError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001542
Guido van Rossum60279da1992-04-02 10:24:59 +00001543\section{Bitwise operations}
1544
1545Each of the three bitwise operations has a different priority level:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001546
1547\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001548and_expr: shift_expr | and_expr "&" shift_expr
Guido van Rossum743d1e71992-01-07 16:43:53 +00001549xor_expr: and_expr | xor_expr "^" and_expr
Guido van Rossum743d1e71992-01-07 16:43:53 +00001550or_expr: xor_expr | or_expr "|" xor_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001551\end{verbatim}
1552
Guido van Rossum60279da1992-04-02 10:24:59 +00001553The \verb\"&"\ operator yields the bitwise AND of its arguments, which
1554must be plain or long integers. The arguments are converted to a
1555common type.
1556
1557The \verb\"~"\ operator yields the bitwise XOR (exclusive OR) of its
1558arguments, which must be plain or long integers. The arguments are
1559converted to a common type.
1560
1561The \verb\"|"\ operator yields the bitwise (inclusive) OR of its
1562arguments, which must be plain or long integers. The arguments are
1563converted to a common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001564
1565\section{Comparisons}
1566
Guido van Rossum60279da1992-04-02 10:24:59 +00001567Contrary to C, all comparison operations in Python have the same
1568priority, which is lower than that of any arithmetic, shifting or
1569bitwise operation. Also contrary to C, expressions like
1570\verb\a < b < c\ have the interpretation that is conventional in
1571mathematics:
1572
Guido van Rossumf2612d11991-11-21 13:53:03 +00001573\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001574comparison: or_expr (comp_operator or_expr)*
Guido van Rossum743d1e71992-01-07 16:43:53 +00001575comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001576\end{verbatim}
1577
1578Comparisons yield integer value: 1 for true, 0 for false.
1579
1580Comparisons can be chained arbitrarily,
1581e.g., $x < y <= z$ is equivalent to
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001582$x < y$ \verb\and\ $y <= z$, except that $y$ is evaluated only once
Guido van Rossumf2612d11991-11-21 13:53:03 +00001583(but in both cases $z$ is not evaluated at all when $x < y$ is
1584found to be false).
1585
1586Formally, $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 +00001587$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 +00001588$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
1589
1590Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
1591between $e_0$ and $e_2$, e.g., $x < y > z$ is perfectly legal.
1592
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001593The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with
1594C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below
1595\verb\<>\ is also implied.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001596
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001597The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
Guido van Rossumf2612d11991-11-21 13:53:03 +00001598the values of two objects. The objects needn't have the same type.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001599If both are numbers, they are coverted to a common type. Otherwise,
1600objects of different types {\em always} compare unequal, and are
1601ordered consistently but arbitrarily.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001602
1603(This unusual
1604definition of comparison is done to simplify the definition of
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001605operations like sorting and the \verb\in\ and \verb\not in\ operators.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001606
1607Comparison of objects of the same type depends on the type:
1608
1609\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001610
1611\item
1612Numbers are compared arithmetically.
1613
1614\item
1615Strings are compared lexicographically using the numeric equivalents
1616(the result of the built-in function \verb\ord\) of their characters.
1617
1618\item
1619Tuples and lists are compared lexicographically using comparison of
1620corresponding items.
1621
1622\item
1623Mappings (dictionaries) are compared through lexicographic
1624comparison of their sorted (key, value) lists.%
1625\footnote{This is expensive since it requires sorting the keys first,
1626but about the only sensible definition. It was tried to compare
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00001627dictionaries by identity only, but this caused surprises because
1628people expected to be able to test a dictionary for emptiness by
1629comparing it to {\tt \{\}}.}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001630
1631\item
1632Most other types compare unequal unless they are the same object;
1633the choice whether one object is considered smaller or larger than
1634another one is made arbitrarily but consistently within one
1635execution of a program.
1636
Guido van Rossumf2612d11991-11-21 13:53:03 +00001637\end{itemize}
1638
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001639The operators \verb\in\ and \verb\not in\ test for sequence
1640membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and
1641only if there exists an index $i$ such that $x = y[i]$.
1642$x ~\verb\not in\~ y$ yields the inverse truth value. The exception
1643\verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is
1644a string and $x$ is not a string of length one.%
1645\footnote{The latter restriction is sometimes a nuisance.}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001646
1647The operators \verb\is\ and \verb\is not\ compare object identity:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001648$x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same
1649object. $x ~\verb\is not\~ y$ yields the inverse truth value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001650
Guido van Rossum60279da1992-04-02 10:24:59 +00001651\section{Boolean operations} \label{Booleans}
1652
1653Boolean operations have the lowest priority of all Python operations:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001654
1655\begin{verbatim}
1656condition: or_test
Guido van Rossum743d1e71992-01-07 16:43:53 +00001657or_test: and_test | or_test "or" and_test
1658and_test: not_test | and_test "and" not_test
1659not_test: comparison | "not" not_test
Guido van Rossumf2612d11991-11-21 13:53:03 +00001660\end{verbatim}
1661
Guido van Rossum60279da1992-04-02 10:24:59 +00001662In the context of Boolean operations, and also when conditions are
1663used by control flow statements, the following values are interpreted
1664as false: \verb\None\, numeric zero of all types, empty sequences
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001665(strings, tuples and lists), and empty mappings (dictionaries). All
1666other values are interpreted as true.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001667
1668The operator \verb\not\ yields 1 if its argument is false, 0 otherwise.
1669
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001670The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false,
Guido van Rossum60279da1992-04-02 10:24:59 +00001671its value is returned; otherwise, $y$ is evaluated and the resulting
1672value is returned.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001673
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001674The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true,
Guido van Rossum60279da1992-04-02 10:24:59 +00001675its value is returned; otherwise, $y$ is evaluated and the resulting
1676value is returned.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001677
1678(Note that \verb\and\ and \verb\or\ do not restrict the value and type
1679they return to 0 and 1, but rather return the last evaluated argument.
Guido van Rossum60279da1992-04-02 10:24:59 +00001680This is sometimes useful, e.g. if \verb\s\ is a string that should be
1681replaced by a default value if it is empty, the expression
1682\verb\s or 'foo'\ yields the desired value. Because \verb\not\ has to
1683invent a value anyway, it does not bother to return a value of the
1684same type as its argument, so e.g. \verb\not 'foo'\ yields \verb\0\,
1685not \verb\''\.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001686
1687\section{Expression lists and condition lists}
1688
1689\begin{verbatim}
1690expr_list: or_expr ("," or_expr)* [","]
1691cond_list: condition ("," condition)* [","]
1692\end{verbatim}
1693
1694The only difference between expression lists and condition lists is
1695the lowest priority of operators that can be used in them without
1696being enclosed in parentheses; condition lists allow all operators,
1697while expression lists don't allow comparisons and Boolean operators
1698(they do allow bitwise and shift operators though).
1699
1700Expression lists are used in expression statements and assignments;
Guido van Rossum60279da1992-04-02 10:24:59 +00001701condition lists are used everywhere else where a list of
1702comma-separated values is required.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001703
1704An expression (condition) list containing at least one comma yields a
1705tuple. The length of the tuple is the number of expressions
1706(conditions) in the list. The expressions (conditions) are evaluated
Guido van Rossum60279da1992-04-02 10:24:59 +00001707from left to right. (Conditions lists are used syntactically is a few
1708places where no tuple is constructed but a list of values is needed
1709nevertheless.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001710
1711The trailing comma is required only to create a single tuple (a.k.a. a
1712{\em singleton}); it is optional in all other cases. A single
1713expression (condition) without a trailing comma doesn't create a
1714tuple, but rather yields the value of that expression (condition).
1715
Guido van Rossum60279da1992-04-02 10:24:59 +00001716(To create an empty tuple, use an empty pair of parentheses:
1717\verb\()\.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001718
1719\chapter{Simple statements}
1720
1721Simple statements are comprised within a single logical line.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001722Several simple statements may occur on a single line separated
Guido van Rossumf2612d11991-11-21 13:53:03 +00001723by semicolons. The syntax for simple statements is:
1724
1725\begin{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001726simple_stmt: expression_stmt
Guido van Rossum60279da1992-04-02 10:24:59 +00001727 | assignment_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001728 | pass_stmt
1729 | del_stmt
1730 | print_stmt
1731 | return_stmt
1732 | raise_stmt
1733 | break_stmt
1734 | continue_stmt
1735 | import_stmt
Guido van Rossum743d1e71992-01-07 16:43:53 +00001736 | global_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001737\end{verbatim}
1738
1739\section{Expression statements}
1740
Guido van Rossum60279da1992-04-02 10:24:59 +00001741Expression statements are used (mostly interactively) to compute and
1742write a value, or (usually) to call a procedure (a function that
1743returns no meaningful result; in Python, procedures return the value
1744\verb\None\):
1745
Guido van Rossumf2612d11991-11-21 13:53:03 +00001746\begin{verbatim}
1747expression_stmt: expression_list
1748\end{verbatim}
1749
Guido van Rossum60279da1992-04-02 10:24:59 +00001750An expression statement evaluates the expression list (which may be a
1751single expression). If the value is not \verb\None\, it is converted
1752to a string using the rules for string conversions (expressions in
1753reverse quotes), and the resulting string is written to standard
1754output on a line by itself.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001755
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001756(The exception for \verb\None\ is made so that procedure calls, which
1757are syntactically equivalent to expressions, do not cause any output.
1758A tuple with only \verb\None\ items is written normally.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001759
Guido van Rossum60279da1992-04-02 10:24:59 +00001760\section{Assignment statements}
1761
1762Assignment statements are used to (re)bind names to values and to
1763modify attributes or items of mutable objects:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001764
1765\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001766assignment_stmt: (target_list "=")+ expression_list
1767target_list: target ("," target)* [","]
1768target: identifier | "(" target_list ")" | "[" target_list "]"
1769 | attributeref | subscription | slicing
Guido van Rossumf2612d11991-11-21 13:53:03 +00001770\end{verbatim}
1771
Guido van Rossum60279da1992-04-02 10:24:59 +00001772(See section \ref{primaries} for the syntax definitions for the last
Guido van Rossumf2612d11991-11-21 13:53:03 +00001773three symbols.)
1774
Guido van Rossum60279da1992-04-02 10:24:59 +00001775An assignment statement evaluates the expression list (remember that
1776this can be a single expression or a comma-separated list, the latter
1777yielding a tuple) and assigns the single resulting object to each of
1778the target lists, from left to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001779
Guido van Rossum60279da1992-04-02 10:24:59 +00001780Assignment is defined recursively depending on the form of the target
1781(list). When a target is part of a mutable object (an attribute
1782reference, subscription or slicing), the mutable object must
1783ultimately perform the assignment and decide about its validity, and
1784may raise an exception if the assignment is unacceptable. The rules
1785observed by various types and the exceptions raised are given with the
1786definition of the object types (see section \ref{types}).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001787
Guido van Rossum60279da1992-04-02 10:24:59 +00001788Assignment of an object to a target list is recursively defined as
1789follows.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001790
1791\begin{itemize}
1792\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001793If the target list is a single target: the object is assigned to that
1794target.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001795
1796\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001797If the target list is a comma-separated list of targets: the object
1798must be a tuple with the same number of items as the list contains
1799targets, and the items are assigned, from left to right, to the
1800corresponding targets.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001801
1802\end{itemize}
1803
Guido van Rossum60279da1992-04-02 10:24:59 +00001804Assignment of an object to a (simple) target is recursively defined as
1805follows.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001806
1807\begin{itemize}
1808
1809\item
1810If the target is an identifier (name):
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001811\begin{itemize}
1812\item
1813If the name does not occur in a \verb\global\ statement in the current
Guido van Rossum60279da1992-04-02 10:24:59 +00001814code block: the name is bound to the object in the current local name
1815space.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001816\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001817Otherwise: the name is bound to the object in the current global name
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001818space.
1819\end{itemize}
Guido van Rossum60279da1992-04-02 10:24:59 +00001820The name is rebound if it was already bound.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001821
1822\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001823If the target is a target list enclosed in parentheses: the object is
1824assigned to that target list as described above.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001825
1826\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001827If the target is a target list enclosed in square brackets: the object
1828must be a list with the same number of items as the target list
1829contains targets, and its items are assigned, from left to right, to
1830the corresponding targets.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001831
1832\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001833If the target is an attribute reference: The primary expression in the
1834reference is evaluated. It should yield an object with assignable
1835attributes; if this is not the case, \verb\TypeError\ is raised. That
1836object is then asked to assign the assigned object to the given
1837attribute; if it cannot perform the assignment, it raises an exception
1838(usually but not necessarily \verb\AttributeError\).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001839
1840\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001841If the target is a subscription: The primary expression in the
1842reference is evaluated. It should yield either a mutable sequence
1843(list) object or a mapping (dictionary) object. Next, the subscript
1844expression is evaluated.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001845
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001846If the primary is a sequence object, the subscript must yield a plain
1847integer. If it is negative, the sequence's length is added to it.
1848The resulting value must be a nonnegative integer less than the
1849sequence's length, and the sequence is asked to assign the assigned
1850object to its item with that index. If the index is out of range,
1851\verb\IndexError\ is raised (assignment to a subscripted sequence
1852cannot add new items to a list).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001853
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001854If the primary is a mapping object, the subscript must have a type
1855compatible with the mapping's key type, and the mapping is then asked
1856to to create a key/datum pair which maps the subscript to the assigned
1857object. This can either replace an existing key/value pair with the
1858same key value, or insert a new key/value pair (if no key with the
1859same value existed).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001860
1861\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001862If the target is a slicing: The primary expression in the reference is
1863evaluated. It should yield a mutable sequence (list) object. The
1864assigned object should be a sequence object of the same type. Next,
1865the lower and upper bound expressions are evaluated, insofar they are
1866present; defaults are zero and the sequence's length. The bounds
1867should evaluate to (small) integers. If either bound is negative, the
1868sequence's length is added to it. The resulting bounds are clipped to
1869lie between zero and the sequence's length, inclusive. Finally, the
1870sequence object is asked to replace the items indicated by the slice
1871with the items of the assigned sequence. This may change the
1872sequence's length, if it allows it.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001873
1874\end{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001875
Guido van Rossumf2612d11991-11-21 13:53:03 +00001876(In the original implementation, the syntax for targets is taken
1877to be the same as for expressions, and invalid syntax is rejected
1878during the code generation phase, causing less detailed error
1879messages.)
1880
Guido van Rossum68c172e1992-01-21 11:34:56 +00001881\section{The {\tt pass} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001882
1883\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001884pass_stmt: "pass"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001885\end{verbatim}
1886
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001887\verb\pass\ is a null operation --- when it is executed, nothing
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001888happens. It is useful as a placeholder when a statement is
1889required syntactically, but no code needs to be executed, for example:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001890
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001891\begin{verbatim}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001892def f(arg): pass # a function that does nothing (yet)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001893
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001894class C: pass # an class with no methods (yet)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001895\end{verbatim}
1896
Guido van Rossum68c172e1992-01-21 11:34:56 +00001897\section{The {\tt del} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001898
1899\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001900del_stmt: "del" target_list
Guido van Rossumf2612d11991-11-21 13:53:03 +00001901\end{verbatim}
1902
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001903Deletion is recursively defined very similar to the way assignment is
1904defined. Rather that spelling it out in full details, here are some
1905hints.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001906
1907Deletion of a target list recursively deletes each target,
1908from left to right.
1909
1910Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001911from the local or global name space, depending on whether the name
1912occurs in a \verb\global\ statement in the same code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001913
1914Deletion of attribute references, subscriptions and slicings
1915is passed to the primary object involved; deletion of a slicing
1916is in general equivalent to assignment of an empty slice of the
1917right type (but even this is determined by the sliced object).
1918
Guido van Rossum68c172e1992-01-21 11:34:56 +00001919\section{The {\tt print} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001920
1921\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001922print_stmt: "print" [ condition ("," condition)* [","] ]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001923\end{verbatim}
1924
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001925\verb\print\ evaluates each condition in turn and writes the resulting
1926object to standard output (see below). If an object is not a string,
1927it is first converted to a string using the rules for string
1928conversions. The (resulting or original) string is then written. A
1929space is written before each object is (converted and) written, unless
1930the output system believes it is positioned at the beginning of a
1931line. This is the case: (1) when no characters have yet been written
1932to standard output; or (2) when the last character written to standard
1933output is \verb/\n/; or (3) when the last write operation on standard
1934output was not a \verb\print\ statement. (In some cases it may be
1935functional to write an empty string to standard output for this
1936reason.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001937
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001938A \verb/"\n"/ character is written at the end, unless the \verb\print\
1939statement ends with a comma. This is the only action if the statement
1940contains just the keyword \verb\print\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001941
1942Standard output is defined as the file object named \verb\stdout\
1943in the built-in module \verb\sys\. If no such object exists,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001944or if it is not a writable file, a \verb\RuntimeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001945(The original implementation attempts to write to the system's original
1946standard output instead, but this is not safe, and should be fixed.)
1947
Guido van Rossum68c172e1992-01-21 11:34:56 +00001948\section{The {\tt return} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001949
1950\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001951return_stmt: "return" [condition_list]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001952\end{verbatim}
1953
1954\verb\return\ may only occur syntactically nested in a function
1955definition, not within a nested class definition.
1956
1957If a condition list is present, it is evaluated, else \verb\None\
1958is substituted.
1959
1960\verb\return\ leaves the current function call with the condition
1961list (or \verb\None\) as return value.
1962
1963When \verb\return\ passes control out of a \verb\try\ statement
1964with a \verb\finally\ clause, that finally clause is executed
1965before really leaving the function.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001966
Guido van Rossum68c172e1992-01-21 11:34:56 +00001967\section{The {\tt raise} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001968
1969\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001970raise_stmt: "raise" condition ["," condition]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001971\end{verbatim}
1972
1973\verb\raise\ evaluates its first condition, which must yield
1974a string object. If there is a second condition, this is evaluated,
1975else \verb\None\ is substituted.
1976
1977It then raises the exception identified by the first object,
1978with the second one (or \verb\None\) as its parameter.
1979
Guido van Rossum68c172e1992-01-21 11:34:56 +00001980\section{The {\tt break} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001981
1982\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001983break_stmt: "break"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001984\end{verbatim}
1985
1986\verb\break\ may only occur syntactically nested in a \verb\for\
1987or \verb\while\ loop, not nested in a function or class definition.
1988
1989It terminates the neares enclosing loop, skipping the optional
1990\verb\else\ clause if the loop has one.
1991
1992If a \verb\for\ loop is terminated by \verb\break\, the loop control
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001993target keeps its current value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001994
1995When \verb\break\ passes control out of a \verb\try\ statement
1996with a \verb\finally\ clause, that finally clause is executed
1997before really leaving the loop.
1998
Guido van Rossum68c172e1992-01-21 11:34:56 +00001999\section{The {\tt continue} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002000
2001\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002002continue_stmt: "continue"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002003\end{verbatim}
2004
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002005\verb\continue\ may only occur syntactically nested in a \verb\for\ or
2006\verb\while\ loop, not nested in a function or class definition, and
2007not nested in the \verb\try\ clause of a \verb\try\ statement with a
2008\verb\finally\ clause (it may occur nested in a \verb\except\ or
2009\verb\finally\ clause of a \verb\try\ statement though).
Guido van Rossumf2612d11991-11-21 13:53:03 +00002010
2011It continues with the next cycle of the nearest enclosing loop.
2012
Guido van Rossum862c6f11992-01-29 14:47:05 +00002013\section{The {\tt import} statement} \label{import}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002014
2015\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002016import_stmt: "import" identifier ("," identifier)*
2017 | "from" identifier "import" identifier ("," identifier)*
2018 | "from" identifier "import" "*"
2019\end{verbatim}
2020
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002021Import statements are executed in two steps: (1) find a module, and
2022initialize it if necessary; (2) define a name or names in the local
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002023name space (of the scope where the \verb\import\ statement occurs).
2024The first form (without \verb\from\) repeats these steps for each
2025identifier in the list, the \verb\from\ form performs them once, with
2026the first identifier specifying the module name.
Guido van Rossum743d1e71992-01-07 16:43:53 +00002027
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002028The system maintains a table of modules that have been initialized,
2029indexed by module name. (The current implementation makes this table
2030accessible as \verb\sys.modules\.) When a module name is found in
2031this table, step (1) is finished. If not, a search for a module
2032definition is started. This first looks for a built-in module
2033definition, and if no built-in module if the given name is found, it
2034searches a user-specified list of directories for a file whose name is
2035the module name with extension \verb\".py"\. (The current
2036implementation uses the list of strings \verb\sys.path\ as the search
2037path; it is initialized from the shell environment variable
2038\verb\$PYTHONPATH\, with an installation-dependent default.)
2039
2040If a built-in module is found, its built-in initialization code is
2041executed and step (1) is finished. If no matching file is found,
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002042\verb\ImportError\ is raised. If a file is found, it is parsed,
2043yielding an executable code block. If a syntax error occurs,
2044\verb\SyntaxError\ is raised. Otherwise, an empty module of the given
2045name is created and inserted in the module table, and then the code
2046block is executed in the context of this module. Exceptions during
2047this execution terminate step (1).
2048
2049When step (1) finishes without raising an exception, step (2) can
2050begin.
2051
2052The first form of \verb\import\ statement binds the module name in the
2053local name space to the module object, and then goes on to import the
2054next identifier, if any. The \verb\from\ from does not bind the
2055module name: it goes through the list of identifiers, looks each one
2056of them up in the module found in step (1), and binds the name in the
2057local name space to the object thus found. If a name is not found,
2058\verb\ImportError\ is raised. If the list of identifiers is replaced
2059by a star (\verb\*\), all names defined in the module are bound,
2060except those beginning with an underscore(\verb\_\).
2061
2062Names bound by import statements may not occur in \verb\global\
2063statements in the same scope.
2064
2065The \verb\from\ form with \verb\*\ may only occur in a module scope.
2066
2067(The current implementation does not enforce the latter two
2068restrictions, but programs should not abuse this freedom, as future
2069implementations may enforce them or silently change the meaning of the
2070program.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002071
Guido van Rossum862c6f11992-01-29 14:47:05 +00002072\section{The {\tt global} statement} \label{global}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002073
2074\begin{verbatim}
2075global_stmt: "global" identifier ("," identifier)*
Guido van Rossumf2612d11991-11-21 13:53:03 +00002076\end{verbatim}
2077
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002078The \verb\global\ statement is a declaration which holds for the
2079entire current scope. It means that the listed identifiers are to be
2080interpreted as globals. While {\em using} global names is automatic
2081if they are not defined in the local scope, {\em assigning} to global
2082names would be impossible without \verb\global\.
2083
2084Names listed in a \verb\global\ statement must not be used in the same
2085scope before that \verb\global\ statement is executed.
2086
2087Name listed in a \verb\global\ statement must not be defined as formal
2088parameters or in a \verb\for\ loop control target, \verb\class\
2089definition, function definition, or \verb\import\ statement.
2090
2091(The current implementation does not enforce the latter two
2092restrictions, but programs should not abuse this freedom, as future
2093implementations may enforce them or silently change the meaning of the
2094program.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00002095
2096\chapter{Compound statements}
2097
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002098Compound statements contain (groups of) other statements; they affect
Guido van Rossum60279da1992-04-02 10:24:59 +00002099or control the execution of those other statements in some way. In
2100general, compound statements span multiple lines, although in simple
2101incarnations a whole compound statement may be contained in one line.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002102
2103The \verb\if\, \verb\while\ and \verb\for\ statements implement
2104traditional control flow constructs. \verb\try\ specifies exception
2105handlers and/or cleanup code for a group of statements. Function and
2106class definitions are also syntactically compound statements.
2107
2108Compound statements consist of one or more `clauses'. A clause
2109consists of a header and a `suite'. The clause headers of a
Guido van Rossum60279da1992-04-02 10:24:59 +00002110particular compound statement are all at the same indentation level.
2111Each clause header begins with a uniquely identifying keyword and ends
2112with a colon. A suite is a group of statements controlled by a
2113clause. A suite can be one or more semicolon-separated simple
2114statements on the same line as the header, following the header's
2115colon, or it can be one or more indented statements on subsequent
2116lines. Only the latter form of suite can contain nested compound
2117statements; the following is illegal, mostly because it wouldn't be
2118clear to which \verb\if\ clause a following \verb\else\ clause would
2119belong:
Guido van Rossumf2612d11991-11-21 13:53:03 +00002120
2121\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002122if test1: if test2: print x
Guido van Rossumf2612d11991-11-21 13:53:03 +00002123\end{verbatim}
2124
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002125Also note that the semicolon binds tighter that the colon in this
Guido van Rossum60279da1992-04-02 10:24:59 +00002126context, so that in the following example, either all or none of the
2127\verb\print\ statements are executed:
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002128
2129\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00002130if x < y < z: print x; print y; print z
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002131\end{verbatim}
2132
2133Summarizing:
2134
2135\begin{verbatim}
2136compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
2137suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
2138statement: stmt_list NEWLINE | compound_stmt
2139stmt_list: simple_stmt (";" simple_stmt)* [";"]
2140\end{verbatim}
2141
2142Note that statements always ends in a \verb\NEWLINE\ possibly followed
2143by a \verb\DEDENT\.
2144
2145Also note that optional continuation clauses always begin with a
2146keyword that cannot start a statement, thus there are no ambiguities
2147(the `dangling \verb\else\' problem is solved in Python by requiring
2148nested \verb\if\ statements to be indented).
2149
Guido van Rossum60279da1992-04-02 10:24:59 +00002150The formatting of the grammar rules in the following sections places
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002151each clause on a separate line for clarity.
2152
Guido van Rossum68c172e1992-01-21 11:34:56 +00002153\section{The {\tt if} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002154
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002155The \verb\if\ statement is used for conditional execution:
2156
Guido van Rossumf2612d11991-11-21 13:53:03 +00002157\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002158if_stmt: "if" condition ":" suite
2159 ("elif" condition ":" suite)*
2160 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002161\end{verbatim}
2162
Guido van Rossum60279da1992-04-02 10:24:59 +00002163It selects exactly one of the suites by evaluating the conditions one
2164by one until one is found to be true (see section \ref{Booleans} for
2165the definition of true and false); then that suite is executed (and no
2166other part of the \verb\if\ statement is executed or evaluated). If
2167all conditions are false, the suite of the \verb\else\ clause, if
2168present, is executed.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002169
Guido van Rossum68c172e1992-01-21 11:34:56 +00002170\section{The {\tt while} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002171
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002172The \verb\while\ statement is used for repeated execution as long as a
2173condition is true:
2174
Guido van Rossumf2612d11991-11-21 13:53:03 +00002175\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002176while_stmt: "while" condition ":" suite
2177 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002178\end{verbatim}
2179
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002180This repeatedly tests the condition and, if it is true, executes the
2181first suite; if the condition is false (which may be the first time it
Guido van Rossum60279da1992-04-02 10:24:59 +00002182is tested) the suite of the \verb\else\ clause, if present, is
2183executed and the loop terminates.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002184
2185A \verb\break\ statement executed in the first suite terminates the
2186loop without executing the \verb\else\ clause's suite. A
2187\verb\continue\ statement executed in the first suited skips the rest
2188of the suite and goes back to testing the condition.
2189
Guido van Rossum68c172e1992-01-21 11:34:56 +00002190\section{The {\tt for} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002191
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002192The \verb\for\ statement is used to iterate over the elements of a
2193sequence (string, tuple or list):
2194
Guido van Rossumf2612d11991-11-21 13:53:03 +00002195\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002196for_stmt: "for" target_list "in" condition_list ":" suite
2197 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002198\end{verbatim}
2199
Guido van Rossum60279da1992-04-02 10:24:59 +00002200The condition list is evaluated once; it should yield a sequence. The
2201suite is then executed once for each item in the sequence, in the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002202order of ascending indices. Each item in turn is assigned to the
2203target list using the standard rules for assignments, and then the
Guido van Rossum60279da1992-04-02 10:24:59 +00002204suite is executed. When the items are exhausted (which is immediately
2205when the sequence is empty), the suite in the \verb\else\ clause, if
2206present, is executed, and the loop terminates.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002207
2208A \verb\break\ statement executed in the first suite terminates the
2209loop without executing the \verb\else\ clause's suite. A
2210\verb\continue\ statement executed in the first suited skips the rest
Guido van Rossum60279da1992-04-02 10:24:59 +00002211of the suite and continues with the next item, or with the \verb\else\
2212clause if there was no next item.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002213
2214The suite may assign to the variable(s) in the target list; this does
2215not affect the next item assigned to it.
2216
Guido van Rossum60279da1992-04-02 10:24:59 +00002217The target list is not deleted when the loop is finished, but if the
2218sequence is empty, it will not have been assigned to at all by the
2219loop.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002220
Guido van Rossum60279da1992-04-02 10:24:59 +00002221Hint: the built-in function \verb\range()\ returns a sequence of
2222integers suitable to emulate the effect of Pascal's \verb\for i := a
2223to b do\; e.g. \verb\range(3)\ returns the list \verb\[0, 1, 2]\.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002224
2225{\bf Warning:} There is a subtlety when the sequence is being modified
Guido van Rossum60279da1992-04-02 10:24:59 +00002226by the loop (this can only occur for mutable sequences, i.e. lists).
2227An internal counter is used to keep track of which item is used next,
2228and this is incremented on each iteration. When this counter has
2229reached the length of the sequence the loop terminates. This means that
2230if the suite deletes the current (or a previous) item from the
2231sequence, the next item will be skipped (since it gets the index of
2232the current item which has already been treated). Likewise, if the
2233suite inserts an item in the sequence before the current item, the
2234current item will be treated again the next time through the loop.
2235This can lead to nasty bugs that can be avoided by making a temporary
2236copy using a slice of the whole sequence, e.g.
2237
2238\begin{verbatim}
2239for x in a[:]:
2240 if x < 0: a.remove(x)
2241\end{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002242
Guido van Rossum68c172e1992-01-21 11:34:56 +00002243\section{The {\tt try} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002244
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002245The \verb\try\ statement specifies exception handlers and/or cleanup
2246code for a group of statements:
2247
Guido van Rossumf2612d11991-11-21 13:53:03 +00002248\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00002249try_stmt: try_exc_stmt | try_fin_stmt
2250try_exc_stmt: "try" ":" suite
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002251 ("except" condition ["," target] ":" suite)*
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002252 ["except" ":" suite]
Guido van Rossum60279da1992-04-02 10:24:59 +00002253try_fin_stmt: "try" ":" suite
2254 "finally" ":" suite
Guido van Rossumf2612d11991-11-21 13:53:03 +00002255\end{verbatim}
2256
Guido van Rossum60279da1992-04-02 10:24:59 +00002257There are two forms of \verb\try\ statement: \verb\try...except\ and
2258\verb\try...finally\. These forms cannot be mixed. A \verb\try\
2259clause with neither a \verb\except\ clause nor a \verb\finally\ clause
2260just executes the suite of statements in its \verb\try\ clause (it
2261could be forbidden syntactically but there seems little reason to do
2262so).
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002263
2264The \verb\try...except\ form specifies one or more exception handlers.
2265When no exception occurs in the \verb\try\ clause, no exception
2266handler is executed. When an exception occurs in the \verb\try\
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002267suite, a search for an exception handler is started. This inspects
2268the except clauses (exception handlers) in turn until one is found
2269that matches the exception. A condition-less except clause (which
2270must be last) matches any exception. For except clause with a
2271condition, that condition is evaluated, and the clause matches the
2272exception if the resulting object is ``compatible'' with the
2273exception. An object is compatible with an exception if it is either
2274the object that identifies the exception or it is a tuple containing
2275an item that is compatible with the exception.
2276
2277If no except clause matches the exception, the search for an exception
2278handler continues in the surrounding code and on the invocation stack.
2279
2280If the evaluation of a condition in the header of an except clause
2281raises an exception, the original search for a handler is cancelled
2282and a search starts for the new exception in the surrounding code and
2283on the call stack.
2284
2285When a matching except clause is found in a try statement, the
2286exception's parameter is assigned to the target specified in the
2287except clause (if present), and the except clause's suite is executed.
2288When the end of this suite is reached, execution continues normally
2289at the point following the entire try statement. (This means that if
2290two nested handlers exist for the same exception, and the exception
2291occurs in the try clause of the inner handler, the outer handler will
2292not notice the exception.)
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002293
2294The \verb\try...finally\ form specifies a `cleanup' handler. The
2295\verb\try\ clause is executed. When no exception occurs, the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002296\verb\finally\ clause is executed. When an exception occurs in the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002297\verb\try\ clause, the exception is temporarily saved, the
2298\verb\finally\ clause is executed, and then the saved exception is
2299re-raised. If the \verb\finally\ clause raises another exception or
2300executes a \verb\return\, \verb\break\ or \verb\continue\ statement,
2301the saved exception is lost.
2302
2303When a \verb\return\ or \verb\break\ statement is executed in the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002304\verb\try\ suite of a \verb\try...finally\ statement, the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002305\verb\finally\ clause is also executed `on the way out'. A
2306\verb\continue\ statement is illegal in the \verb\try\ clause (the
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002307reason is a problem with the current implementation --- this
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002308restriction may be lifted in the future).
2309
Guido van Rossum862c6f11992-01-29 14:47:05 +00002310\section{Function definitions} \label{function}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002311
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002312A function definition defines a function:
Guido van Rossumf2612d11991-11-21 13:53:03 +00002313
2314\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002315funcdef: "def" identifier "(" [parameter_list] ")" ":" suite
2316parameter_list: parameter ("," parameter)*
2317parameter: identifier | "(" parameter_list ")"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002318\end{verbatim}
2319
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002320A function definition is an executable statement. Its execution binds
2321the function name in the current local name space to a function object
2322(a wrapper around the executable code for the function). This
2323function object contains a reference to the current global name space
2324as the global name space to be used when the function is called.
2325
2326The function definition does not execute the function body; this gets
2327executed only when the function is called. Function call semantics
2328are described elsewhere (see XXX).
Guido van Rossum862c6f11992-01-29 14:47:05 +00002329
2330\section{Class definitions} \label{class}
2331
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002332A class definition defines a class:
Guido van Rossumf2612d11991-11-21 13:53:03 +00002333
2334\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002335classdef: "class" identifier [inheritance] ":" suite
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002336inheritance: "(" condition_list ")"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002337\end{verbatim}
2338
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002339A class definition is an executable statement. It first executes the
2340inheritance list, if present. The class's suite is executed in a new
2341execution frame, using a newly created local name space and the
2342original global name space. (Usually, the suite contains only
2343function definitions.) When the class's suite finishes execution, its
2344execution frame is discarded but its local name space is saved. A
2345class object (see XXX) is created using the inheritance list for the
2346base classes and the saved local name space for the attribute
2347dictionary. The class name is then bound to this class object in the
2348original local name space.
Guido van Rossum862c6f11992-01-29 14:47:05 +00002349
2350\section{P.M.}
2351
Guido van Rossum743d1e71992-01-07 16:43:53 +00002352XXX New definition of expressions (as conditions)
Guido van Rossumf2612d11991-11-21 13:53:03 +00002353
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002354\chapter{Top-level components}
2355
2356The Python interpreter can get its input from a number of sources:
2357from a script passed to it as standard input or as program argument,
2358typed in interactively, from a module source file, etc. This chapter
2359gives the syntax used in these cases.
2360
2361\section{Complete Python programs}
2362
2363While a language specification need not prescribe how the language
2364interpreter is invoked, it is useful to have a notion of a complete
2365Python program. A complete Python program is executed in a minimally
2366initialized environment: all built-in and standard modules are
2367available, but none have been initialized, except for \verb\sys\
2368(various system services), \verb\builtin\ (built-in functions,
2369exceptions and \verb\None\) and \verb\__main__\. The latter is used
2370to provide the local and global name space for execution of the
2371complete program.
2372
2373The syntax for a complete Python program is that for file input,
2374described in the next section.
2375
2376The interpreter may also be invoked in interactive mode; in this case,
2377it does not read and execute a complete program but reads and executes
2378one statement (possibly compound) at a time. The initial environment
2379is identical to that of a complete program; each statement is executed
2380in the name space of \verb\__main__\.
2381
2382Under {\UNIX}, a complete program can be passed to the interpreter in
2383three forms: with the {\bf -c} {\it string} command line option, as a
2384file passed as the first command line argument, or as standard input.
2385If the file or standard input is a tty device, the interpreter enters
2386interactive mode; otherwise, it executes the file as a complete
2387program.
2388
2389\section{File input}
2390
2391All input read from non-interactive files has the same form:
2392
2393\begin{verbatim}
2394file_input: (NEWLINE | statement)*
2395\end{verbatim}
2396
2397This syntax is used in the following situations:
2398
2399\begin{itemize}
2400
2401\item when parsing a complete Python program (from a file or from a string);
2402
2403\item when parsing a module;
2404
2405\item when parsing a string passed to \verb\exec()\;
2406
2407\item when parsing a file passed to \verb\execfile()\;
2408
2409\end{itemize}
2410
2411\section{Interactive input}
2412
2413Input in interactive mode is parsed using the following grammar:
2414
2415\begin{verbatim}
2416interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE
2417\end{verbatim}
2418
2419Note that a (top-level) compound statement must be followed by a blank
2420line in interactive mode; this is needed to help the parser detect the
2421end of the input.
2422
2423\section{Expression input}
2424
2425There are two forms of expression input. Both ignore leading
2426whitespace.
2427
2428The string argument to \verb\eval()\ must have the following form:
2429
2430\begin{verbatim}
2431eval_input: condition_list NEWLINE*
2432\end{verbatim}
2433
2434The input line read by \verb\input()\ must have the following form:
2435
2436\begin{verbatim}
2437input_input: condition_list NEWLINE
2438\end{verbatim}
2439
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002440\input{ref.ind} % The index
2441
Guido van Rossumf2612d11991-11-21 13:53:03 +00002442\end{document}