blob: 0edec66bca80da94672a3039a6373d65ae1fc093 [file] [log] [blame]
Guido van Rossum37953781992-04-06 14:04:04 +00001\documentstyle[twoside,11pt,myformat]{report}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002
Guido van Rossum862c6f11992-01-29 14:47:05 +00003\title{\bf Python Reference Manual}
4
Guido van Rossumf2612d11991-11-21 13:53:03 +00005\author{
6 Guido van Rossum \\
7 Dept. CST, CWI, Kruislaan 413 \\
8 1098 SJ Amsterdam, The Netherlands \\
9 E-mail: {\tt guido@cwi.nl}
10}
11
Guido van Rossumb5e1c181992-03-06 10:52:59 +000012% Tell \index to actually write the .idx file
13\makeindex
14
Guido van Rossumf2612d11991-11-21 13:53:03 +000015\begin{document}
16
17\pagenumbering{roman}
18
19\maketitle
20
21\begin{abstract}
22
23\noindent
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000024Python is a simple, yet powerful, interpreted programming language
25that bridges the gap between C and shell programming, and is thus
26ideally suited for ``throw-away programming'' and rapid prototyping.
27Its syntax is put together from constructs borrowed from a variety of
28other languages; most prominent are influences from ABC, C, Modula-3
29and Icon.
Guido van Rossumf2612d11991-11-21 13:53:03 +000030
31The Python interpreter is easily extended with new functions and data
32types implemented in C. Python is also suitable as an extension
33language for highly customizable C applications such as editors or
34window managers.
35
36Python is available for various operating systems, amongst which
37several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S.,
38and MS-DOS.
39
40This reference manual describes the syntax and ``core semantics'' of
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000041the language. It is terse, but attempts to be exact and complete.
42The semantics of non-essential built-in object types and of the
43built-in functions and modules are described in the {\em Python
44Library Reference}. For an informal introduction to the language, see
45the {\em Python Tutorial}.
Guido van Rossumf2612d11991-11-21 13:53:03 +000046
47\end{abstract}
48
49\pagebreak
50
Guido van Rossum670e5a01992-01-17 14:03:20 +000051{
52\parskip = 0mm
Guido van Rossumf2612d11991-11-21 13:53:03 +000053\tableofcontents
Guido van Rossum670e5a01992-01-17 14:03:20 +000054}
Guido van Rossumf2612d11991-11-21 13:53:03 +000055
56\pagebreak
57
58\pagenumbering{arabic}
59
60\chapter{Introduction}
61
62This reference manual describes the Python programming language.
63It is not intended as a tutorial.
64
Guido van Rossum743d1e71992-01-07 16:43:53 +000065While I am trying to be as precise as possible, I chose to use English
66rather than formal specifications for everything except syntax and
67lexical analysis. This should make the document better understandable
68to the average reader, but will leave room for ambiguities.
69Consequently, if you were coming from Mars and tried to re-implement
Guido van Rossum7b632a61992-01-16 17:49:21 +000070Python from this document alone, you might have to guess things and in
Guido van Rossumb5e1c181992-03-06 10:52:59 +000071fact you would probably end up implementing quite a different language.
Guido van Rossum7b632a61992-01-16 17:49:21 +000072On the other hand, if you are using
Guido van Rossum743d1e71992-01-07 16:43:53 +000073Python and wonder what the precise rules about a particular area of
Guido van Rossumb5e1c181992-03-06 10:52:59 +000074the language are, you should definitely be able to find them here.
Guido van Rossum743d1e71992-01-07 16:43:53 +000075
76It is dangerous to add too many implementation details to a language
Guido van Rossumb5e1c181992-03-06 10:52:59 +000077reference document --- the implementation may change, and other
Guido van Rossum743d1e71992-01-07 16:43:53 +000078implementations of the same language may work differently. On the
79other hand, there is currently only one Python implementation, and
Guido van Rossum7b632a61992-01-16 17:49:21 +000080its particular quirks are sometimes worth being mentioned, especially
Guido van Rossumb5e1c181992-03-06 10:52:59 +000081where the implementation imposes additional limitations. Therefore,
82you'll find short ``implementation notes'' sprinkled throughout the
83text.
Guido van Rossum743d1e71992-01-07 16:43:53 +000084
85Every Python implementation comes with a number of built-in and
86standard modules. These are not documented here, but in the separate
87{\em Python Library Reference} document. A few built-in modules are
88mentioned when they interact in a significant way with the language
89definition.
90
91\section{Notation}
92
93The descriptions of lexical analysis and syntax use a modified BNF
94grammar notation. This uses the following style of definition:
Guido van Rossumb5e1c181992-03-06 10:52:59 +000095\index{BNF}
96\index{grammar}
97\index{syntax}
98\index{notation}
Guido van Rossum743d1e71992-01-07 16:43:53 +000099
100\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000101name: lc_letter (lc_letter | "_")*
102lc_letter: "a"..."z"
Guido van Rossum743d1e71992-01-07 16:43:53 +0000103\end{verbatim}
104
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000105The first line says that a \verb\name\ is an \verb\lc_letter\ followed by
106a sequence of zero or more \verb\lc_letter\s and underscores. An
107\verb\lc_letter\ in turn is any of the single characters `a' through `z'.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000108(This rule is actually adhered to for the names defined in lexical and
Guido van Rossum743d1e71992-01-07 16:43:53 +0000109grammar rules in this document.)
110
111Each rule begins with a name (which is the name defined by the rule)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000112and a colon. A vertical bar
Guido van Rossum7b632a61992-01-16 17:49:21 +0000113(\verb\|\) is used to separate alternatives; it is the least binding
114operator in this notation. A star (\verb\*\) means zero or more
115repetitions of the preceding item; likewise, a plus (\verb\+\) means
116one or more repetitions, and a question mark (\verb\?\) zero or one
117(in other words, the preceding item is optional). These three
118operators bind as tightly as possible; parentheses are used for
Guido van Rossum743d1e71992-01-07 16:43:53 +0000119grouping. Literal strings are enclosed in double quotes. White space
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000120is only meaningful to separate tokens. Rules are normally contained
121on a single line; rules with many alternatives may be formatted
122alternatively with each line after the first beginning with a
123vertical bar.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000124
125In lexical definitions (as the example above), two more conventions
126are used: Two literal characters separated by three dots mean a choice
127of any single character in the given (inclusive) range of ASCII
128characters. A phrase between angular brackets (\verb\<...>\) gives an
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000129informal description of the symbol defined; e.g. this could be used
Guido van Rossum743d1e71992-01-07 16:43:53 +0000130to describe the notion of `control character' if needed.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000131\index{lexical definitions}
132\index{ASCII}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000133
Guido van Rossum7b632a61992-01-16 17:49:21 +0000134Even though the notation used is almost the same, there is a big
Guido van Rossum743d1e71992-01-07 16:43:53 +0000135difference between the meaning of lexical and syntactic definitions:
136a lexical definition operates on the individual characters of the
137input source, while a syntax definition operates on the stream of
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000138tokens generated by the lexical analysis. All uses of BNF in the next
139chapter (``Lexical Analysis'') are lexical definitions; uses in
140subsequenc chapter are syntactic definitions.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000141
Guido van Rossumf2612d11991-11-21 13:53:03 +0000142\chapter{Lexical analysis}
143
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000144A Python program is read by a {\em parser}. Input to the parser is a
145stream of {\em tokens}, generated by the {\em lexical analyzer}. This
146chapter describes how the lexical analyzer breaks a file into tokens.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000147\index{lexical analysis}
148\index{parser}
149\index{token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000150
151\section{Line structure}
152
Guido van Rossum7b632a61992-01-16 17:49:21 +0000153A Python program is divided in a number of logical lines. The end of
154a logical line is represented by the token NEWLINE. Statements cannot
155cross logical line boundaries except where NEWLINE is allowed by the
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000156syntax (e.g. between statements in compound statements).
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000157\index{line structure}
158\index{logical line}
159\index{NEWLINE token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000160
161\subsection{Comments}
162
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000163A comment starts with a hash character (\verb\#\) that is not part of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000164a string literal, and ends at the end of the physical line. A comment
165always signifies the end of the logical line. Comments are ignored by
166the syntax.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000167\index{comment}
168\index{logical line}
169\index{physical line}
170\index{hash character}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000171
172\subsection{Line joining}
173
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000174Two or more physical lines may be joined into logical lines using
Guido van Rossum7b632a61992-01-16 17:49:21 +0000175backslash characters (\verb/\/), as follows: when a physical line ends
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000176in a backslash that is not part of a string literal or comment, it is
177joined with the following forming a single logical line, deleting the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000178backslash and the following end-of-line character. For example:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000179\index{physical line}
180\index{line joining}
181\index{backslash character}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000182%
183\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000184moth_names = ['Januari', 'Februari', 'Maart', \
185 'April', 'Mei', 'Juni', \
186 'Juli', 'Augustus', 'September', \
187 'Oktober', 'November', 'December']
Guido van Rossum670e5a01992-01-17 14:03:20 +0000188\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000189
190\subsection{Blank lines}
191
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000192A logical line that contains only spaces, tabs, and possibly a
193comment, is ignored (i.e., no NEWLINE token is generated), except that
194during interactive input of statements, an entirely blank logical line
195terminates a multi-line statement.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000196\index{blank line}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000197
198\subsection{Indentation}
199
Guido van Rossum7b632a61992-01-16 17:49:21 +0000200Leading whitespace (spaces and tabs) at the beginning of a logical
201line is used to compute the indentation level of the line, which in
202turn is used to determine the grouping of statements.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000203\index{indentation}
204\index{whitespace}
205\index{leading whitespace}
206\index{space}
207\index{tab}
208\index{grouping}
209\index{statement grouping}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000210
Guido van Rossum7b632a61992-01-16 17:49:21 +0000211First, tabs are replaced (from left to right) by one to eight spaces
212such that the total number of characters up to there is a multiple of
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000213eight (this is intended to be the same rule as used by {\UNIX}). The
Guido van Rossum7b632a61992-01-16 17:49:21 +0000214total number of spaces preceding the first non-blank character then
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000215determines the line's indentation. Indentation cannot be split over
216multiple physical lines using backslashes.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000217
218The indentation levels of consecutive lines are used to generate
219INDENT and DEDENT tokens, using a stack, as follows.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000220\index{INDENT token}
221\index{DEDENT token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000222
223Before the first line of the file is read, a single zero is pushed on
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000224the stack; this will never be popped off again. The numbers pushed on
225the stack will always be strictly increasing from bottom to top. At
226the beginning of each logical line, the line's indentation level is
227compared to the top of the stack. If it is equal, nothing happens.
228If it larger, it is pushed on the stack, and one INDENT token is
229generated. If it is smaller, it {\em must} be one of the numbers
230occurring on the stack; all numbers on the stack that are larger are
231popped off, and for each number popped off a DEDENT token is
232generated. At the end of the file, a DEDENT token is generated for
233each number remaining on the stack that is larger than zero.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000234
Guido van Rossum7b632a61992-01-16 17:49:21 +0000235Here is an example of a correctly (though confusingly) indented piece
236of Python code:
237
238\begin{verbatim}
239def perm(l):
Guido van Rossum670e5a01992-01-17 14:03:20 +0000240 # Compute the list of all permutations of l
241
Guido van Rossum7b632a61992-01-16 17:49:21 +0000242 if len(l) <= 1:
243 return [l]
244 r = []
245 for i in range(len(l)):
246 s = l[:i] + l[i+1:]
247 p = perm(s)
248 for x in p:
249 r.append(l[i:i+1] + x)
250 return r
251\end{verbatim}
252
253The following example shows various indentation errors:
254
255\begin{verbatim}
256 def perm(l): # error: first line indented
257 for i in range(len(l)): # error: not indented
258 s = l[:i] + l[i+1:]
259 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
260 for x in p:
261 r.append(l[i:i+1] + x)
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000262 return r # error: inconsistent dedent
Guido van Rossum7b632a61992-01-16 17:49:21 +0000263\end{verbatim}
264
265(Actually, the first three errors are detected by the parser; only the
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000266last error is found by the lexical analyzer --- the indentation of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000267\verb\return r\ does not match a level popped off the stack.)
268
Guido van Rossumf2612d11991-11-21 13:53:03 +0000269\section{Other tokens}
270
271Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
272exist: identifiers, keywords, literals, operators, and delimiters.
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000273Spaces and tabs are not tokens, but serve to delimit tokens. Where
274ambiguity exists, a token comprises the longest possible string that
275forms a legal token, when read from left to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000276
Guido van Rossumf2612d11991-11-21 13:53:03 +0000277\section{Identifiers}
278
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000279Identifiers (also referred to as names) are described by the following
280lexical definitions:
281\index{identifier}
282\index{name}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000283
284\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000285identifier: (letter|"_") (letter|digit|"_")*
Guido van Rossumf2612d11991-11-21 13:53:03 +0000286letter: lowercase | uppercase
Guido van Rossum743d1e71992-01-07 16:43:53 +0000287lowercase: "a"..."z"
288uppercase: "A"..."Z"
289digit: "0"..."9"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000290\end{verbatim}
291
Guido van Rossum670e5a01992-01-17 14:03:20 +0000292Identifiers are unlimited in length. Case is significant.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000293
Guido van Rossum670e5a01992-01-17 14:03:20 +0000294\subsection{Keywords}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000295
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000296The following identifiers are used as reserved words, or {\em
Guido van Rossum7b632a61992-01-16 17:49:21 +0000297keywords} of the language, and cannot be used as ordinary
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000298identifiers. They must be spelled exactly as written here:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000299\index{keyword}
300\index{reserved word}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000301
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000302\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000303and del for in print
304break elif from is raise
305class else global not return
306continue except if or try
307def finally import pass while
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000308\end{verbatim}
309
Guido van Rossum743d1e71992-01-07 16:43:53 +0000310% # This Python program sorts and formats the above table
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000311% import string
312% l = []
313% try:
314% while 1:
315% l = l + string.split(raw_input())
316% except EOFError:
317% pass
318% l.sort()
319% for i in range((len(l)+4)/5):
320% for j in range(i, len(l), 5):
321% print string.ljust(l[j], 10),
322% print
Guido van Rossumf2612d11991-11-21 13:53:03 +0000323
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000324\section{Literals} \label{literals}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000325
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000326Literals are notations for constant values of some built-in types.
327\index{literal}
328\index{constant}
329
Guido van Rossumf2612d11991-11-21 13:53:03 +0000330\subsection{String literals}
331
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000332String literals are described by the following lexical definitions:
333\index{string literal}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000334
335\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000336stringliteral: "'" stringitem* "'"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000337stringitem: stringchar | escapeseq
Guido van Rossum743d1e71992-01-07 16:43:53 +0000338stringchar: <any ASCII character except newline or "\" or "'">
339escapeseq: "'" <any ASCII character except newline>
Guido van Rossumf2612d11991-11-21 13:53:03 +0000340\end{verbatim}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000341\index{ASCII}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000342
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000343String literals cannot span physical line boundaries. Escape
344sequences in strings are actually interpreted according to rules
345simular to those used by Standard C. The recognized escape sequences
346are:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000347\index{physical line}
348\index{escape sequence}
349\index{Standard C}
350\index{C}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000351
352\begin{center}
353\begin{tabular}{|l|l|}
354\hline
355\verb/\\/ & Backslash (\verb/\/) \\
356\verb/\'/ & Single quote (\verb/'/) \\
357\verb/\a/ & ASCII Bell (BEL) \\
358\verb/\b/ & ASCII Backspace (BS) \\
Guido van Rossum7b632a61992-01-16 17:49:21 +0000359%\verb/\E/ & ASCII Escape (ESC) \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000360\verb/\f/ & ASCII Formfeed (FF) \\
361\verb/\n/ & ASCII Linefeed (LF) \\
362\verb/\r/ & ASCII Carriage Return (CR) \\
363\verb/\t/ & ASCII Horizontal Tab (TAB) \\
364\verb/\v/ & ASCII Vertical Tab (VT) \\
365\verb/\/{\em ooo} & ASCII character with octal value {\em ooo} \\
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000366\verb/\x/{\em xx...} & ASCII character with hex value {\em xx...} \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000367\hline
368\end{tabular}
369\end{center}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000370\index{ASCII}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000371
Guido van Rossum7b632a61992-01-16 17:49:21 +0000372In strict compatibility with in Standard C, up to three octal digits are
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000373accepted, but an unlimited number of hex digits is taken to be part of
374the hex escape (and then the lower 8 bits of the resulting hex number
Guido van Rossum7b632a61992-01-16 17:49:21 +0000375are used in all current implementations...).
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000376
Guido van Rossum7b632a61992-01-16 17:49:21 +0000377All unrecognized escape sequences are left in the string unchanged,
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000378i.e., {\em the backslash is left in the string.} (This behavior is
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000379useful when debugging: if an escape sequence is mistyped, the
Guido van Rossum743d1e71992-01-07 16:43:53 +0000380resulting output is more easily recognized as broken. It also helps a
381great deal for string literals used as regular expressions or
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000382otherwise passed to other modules that do their own escape handling.)
383\index{unrecognized escape sequence}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000384
385\subsection{Numeric literals}
386
Guido van Rossum670e5a01992-01-17 14:03:20 +0000387There are three types of numeric literals: plain integers, long
388integers, and floating point numbers.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000389\index{number}
390\index{numeric literal}
391\index{integer literal}
392\index{plain integer literal}
393\index{long integer literal}
394\index{floating point literal}
395\index{hexadecimal literal}
396\index{octal literal}
397\index{decimal literal}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000398
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000399Integer and long integer literals are described by the following
400lexical definitions:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000401
402\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000403longinteger: integer ("l"|"L")
Guido van Rossumf2612d11991-11-21 13:53:03 +0000404integer: decimalinteger | octinteger | hexinteger
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000405decimalinteger: nonzerodigit digit* | "0"
406octinteger: "0" octdigit+
407hexinteger: "0" ("x"|"X") hexdigit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000408
Guido van Rossum743d1e71992-01-07 16:43:53 +0000409nonzerodigit: "1"..."9"
410octdigit: "0"..."7"
411hexdigit: digit|"a"..."f"|"A"..."F"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000412\end{verbatim}
413
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000414Although both lower case `l' and upper case `L' are allowed as suffix
Guido van Rossum670e5a01992-01-17 14:03:20 +0000415for long integers, it is strongly recommended to always use `L', since
416the letter `l' looks too much like the digit `1'.
417
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000418Plain integer decimal literals must be at most $2^{31} - 1$ (i.e., the
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000419largest positive integer, assuming 32-bit arithmetic). Plain octal and
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000420hexadecimal literals may be as large as $2^{32} - 1$, but values
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000421larger than $2^{31} - 1$ are converted to a negative value by
422subtracting $2^{32}$. There is no limit for long integer literals.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000423
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000424Some examples of plain and long integer literals:
Guido van Rossum670e5a01992-01-17 14:03:20 +0000425
426\begin{verbatim}
4277 2147483647 0177 0x80000000
Guido van Rossumb5e1c181992-03-06 10:52:59 +00004283L 79228162514264337593543950336L 0377L 0x100000000L
Guido van Rossum670e5a01992-01-17 14:03:20 +0000429\end{verbatim}
430
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000431Floating point literals are described by the following lexical
432definitions:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000433
434\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000435floatnumber: pointfloat | exponentfloat
436pointfloat: [intpart] fraction | intpart "."
437exponentfloat: (intpart | pointfloat) exponent
Guido van Rossumf2612d11991-11-21 13:53:03 +0000438intpart: digit+
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000439fraction: "." digit+
440exponent: ("e"|"E") ["+"|"-"] digit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000441\end{verbatim}
442
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000443The allowed range of floating point literals is
444implementation-dependent.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000445
446Some examples of floating point literals:
Guido van Rossum7b632a61992-01-16 17:49:21 +0000447
448\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00004493.14 10. .001 1e100 3.14e-10
Guido van Rossum7b632a61992-01-16 17:49:21 +0000450\end{verbatim}
451
Guido van Rossum670e5a01992-01-17 14:03:20 +0000452Note that numeric literals do not include a sign; a phrase like
453\verb\-1\ is actually an expression composed of the operator
Guido van Rossum7b632a61992-01-16 17:49:21 +0000454\verb\-\ and the literal \verb\1\.
455
Guido van Rossumf2612d11991-11-21 13:53:03 +0000456\section{Operators}
457
458The following tokens are operators:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000459\index{operators}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000460
461\begin{verbatim}
462+ - * / %
463<< >> & | ^ ~
Guido van Rossum743d1e71992-01-07 16:43:53 +0000464< == > <= <> != >=
Guido van Rossumf2612d11991-11-21 13:53:03 +0000465\end{verbatim}
466
Guido van Rossum743d1e71992-01-07 16:43:53 +0000467The comparison operators \verb\<>\ and \verb\!=\ are alternate
468spellings of the same operator.
469
Guido van Rossumf2612d11991-11-21 13:53:03 +0000470\section{Delimiters}
471
Guido van Rossum743d1e71992-01-07 16:43:53 +0000472The following tokens serve as delimiters or otherwise have a special
473meaning:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000474\index{delimiters}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000475
476\begin{verbatim}
477( ) [ ] { }
Guido van Rossum743d1e71992-01-07 16:43:53 +0000478; , : . ` =
Guido van Rossumf2612d11991-11-21 13:53:03 +0000479\end{verbatim}
480
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000481The following printing ASCII characters are not used in Python. Their
482occurrence outside string literals and comments is an unconditional
483error:
484\index{ASCII}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000485
486\begin{verbatim}
487! @ $ " ?
488\end{verbatim}
489
Guido van Rossum7b632a61992-01-16 17:49:21 +0000490They may be used by future versions of the language though!
491
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000492\chapter{Data model}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000493
Guido van Rossum743d1e71992-01-07 16:43:53 +0000494\section{Objects, values and types}
495
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000496{\em Objects} are Python's abstraction for data. All data in a Python
497program is represented by objects or by relations between objects.
498(In a sense, and in conformance to Von Neumann's model of a
499``stored program computer'', code is also represented by objects.)
500\index{object}
501\index{data}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000502
503Every object has an identity, a type and a value. An object's {\em
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000504identity} never changes once it has been created; you may think of it
505as the object's address in memory. An object's {\em type} is also
506unchangeable. It determines the operations that an object supports
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000507(e.g. ``does it have a length?'') and also defines the possible
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000508values for objects of that type. The {\em value} of some objects can
509change. Objects whose value can change are said to be {\em mutable};
510objects whose value is unchangeable once they are created are called
511{\em immutable}. The type determines an object's (im)mutability.
512\index{identity of an object}
513\index{value of an object}
514\index{type of an object}
515\index{mutable object}
516\index{immutable object}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000517
518Objects are never explicitly destroyed; however, when they become
Guido van Rossum670e5a01992-01-17 14:03:20 +0000519unreachable they may be garbage-collected. An implementation is
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000520allowed to delay garbage collection or omit it altogether --- it is a
Guido van Rossum670e5a01992-01-17 14:03:20 +0000521matter of implementation quality how garbage collection is
522implemented, as long as no objects are collected that are still
523reachable. (Implementation note: the current implementation uses a
Guido van Rossum743d1e71992-01-07 16:43:53 +0000524reference-counting scheme which collects most objects as soon as they
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000525become unreachable, but never collects garbage containing circular
Guido van Rossum743d1e71992-01-07 16:43:53 +0000526references.)
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000527\index{garbage collection}
528\index{reference counting}
529\index{unreachable object}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000530
Guido van Rossum670e5a01992-01-17 14:03:20 +0000531Note that the use of the implementation's tracing or debugging
532facilities may keep objects alive that would normally be collectable.
533
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000534Some objects contain references to ``external'' resources such as open
535files or windows. It is understood that these resources are freed
536when the object is garbage-collected, but since garbage collection is
537not guaranteed to happen, such objects also provide an explicit way to
538release the external resource, usually a \verb\close\ method.
539Programs are strongly recommended to always explicitly close such
540objects.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000541
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000542Some objects contain references to other objects; these are called
543{\em containers}. Examples of containers are tuples, lists and
544dictionaries. The references are part of a container's value. In
545most cases, when we talk about the value of a container, we imply the
546values, not the identities of the contained objects; however, when we
547talk about the (im)mutability of a container, only the identities of
548the immediately contained objects are implied. (So, if an immutable
549container contains a reference to a mutable object, its value changes
550if that mutable object is changed.)
551\index{container}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000552
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000553Types affect almost all aspects of objects' lives. Even the meaning
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000554of object identity is affected in some sense: for immutable types,
555operations that compute new values may actually return a reference to
556any existing object with the same type and value, while for mutable
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000557objects this is not allowed. E.g. after
Guido van Rossum743d1e71992-01-07 16:43:53 +0000558
559\begin{verbatim}
560a = 1; b = 1; c = []; d = []
561\end{verbatim}
562
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000563\verb\a\ and \verb\b\ may or may not refer to the same object with the
564value one, depending on the implementation, but \verb\c\ and \verb\d\
565are guaranteed to refer to two different, unique, newly created empty
566lists.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000567
Guido van Rossum60279da1992-04-02 10:24:59 +0000568\section{The standard type hierarchy} \label{types}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000569
570Below is a list of the types that are built into Python. Extension
571modules written in C can define additional types. Future versions of
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000572Python may add types to the type hierarchy (e.g. rational or complex
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000573numbers, efficiently stored arrays of integers, etc.).
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000574\index{type}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000575\indexii{data}{type}
576\indexii{type}{hierarchy}
577\indexii{extension}{module}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000578\index{C}
579
580Some of the type descriptions below contain a paragraph listing
581`special attributes'. These are attributes that provide access to the
582implementation and are not intended for general use. Their definition
583may change in the future. There are also some `generic' special
584attributes, not listed with the individual objects: \verb\__methods__\
585is a list of the method names of a built-in object, if it has any;
586\verb\__members__\ is a list of the data attribute names of a built-in
587object, if it has any.
588\index{attribute}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000589\indexii{special}{attribute}
590\indexiii{generic}{special}{attribute}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000591\ttindex{__methods__}
592\ttindex{__members__}
593
594\begin{description}
595
596\item[None]
597This type has a single value. There is a single object with this value.
598This object is accessed through the built-in name \verb\None\.
599It is returned from functions that don't explicitly return an object.
600\ttindex{None}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000601\obindex{None@{\tt None}}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000602
603\item[Numbers]
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000604These are created by numeric literals and returned as results by
605arithmetic operators and arithmetic built-in functions. Numeric
606objects are immutable; once created their value never changes. Python
607numbers are of course strongly related to mathematical numbers, but
608subject to the limitations of numerical representation in computers.
609\obindex{number}
610\obindex{numeric}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000611
612Python distinguishes between integers and floating point numbers:
613
614\begin{description}
615\item[Integers]
616These represent elements from the mathematical set of whole numbers.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000617\obindex{integer}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000618
619There are two types of integers:
620
621\begin{description}
622
623\item[Plain integers]
624These represent numbers in the range $-2^{31}$ through $2^{31}-1$.
625(The range may be larger on machines with a larger natural word
626size, but not smaller.)
627When the result of an operation falls outside this range, the
628exception \verb\OverflowError\ is raised.
629For the purpose of shift and mask operations, integers are assumed to
630have a binary, 2's complement notation using 32 or more bits, and
631hiding no bits from the user (i.e., all $2^{32}$ different bit
632patterns correspond to different values).
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000633\obindex{plain integer}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000634
635\item[Long integers]
636These represent numbers in an unlimited range, subject to avaiable
637(virtual) memory only. For the purpose of shift and mask operations,
638a binary representation is assumed, and negative numbers are
639represented in a variant of 2's complement which gives the illusion of
640an infinite string of sign bits extending to the left.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000641\obindex{long integer}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000642
643\end{description} % Integers
644
645The rules for integer representation are intended to give the most
646meaningful interpretation of shift and mask operations involving
647negative integers and the least surprises when switching between the
648plain and long integer domains. For any operation except left shift,
649if it yields a result in the plain integer domain without causing
650overflow, it will yield the same result in the long integer domain or
651when using mixed operands.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000652\indexii{integer}{representation}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000653
654\item[Floating point numbers]
655These represent machine-level double precision floating point numbers.
656You are at the mercy of the underlying machine architecture and
657C implementation for the accepted range and handling of overflow.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000658\obindex{floating point}
659\indexii{floating point}{number}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000660\index{C}
661
662\end{description} % Numbers
663
664\item[Sequences]
665These represent finite ordered sets indexed by natural numbers.
666The built-in function \verb\len()\ returns the number of elements
667of a sequence. When this number is $n$, the index set contains
668the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence
669\verb\a\ is selected by \verb\a[i]\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000670\obindex{seqence}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000671\bifuncindex{len}
672\index{index operation}
673\index{item selection}
674\index{subscription}
675
676Sequences also support slicing: \verb\a[i:j]\ selects all elements
677with index $k$ such that $i < k < j$. When used as an expression,
678a slice is a sequence of the same type --- this implies that the
679index set is renumbered so that it starts at 0 again.
680\index{slicing}
681
682Sequences are distinguished according to their mutability:
683
684\begin{description}
685%
686\item[Immutable sequences]
687An object of an immutable sequence type cannot change once it is
688created. (If the object contains references to other objects,
689these other objects may be mutable and may be changed; however
690the collection of objects directly referenced by an immutable object
691cannot change.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000692\obindex{immutable sequence}
693\obindex{immutable}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000694
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.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000706The string data type is also used to represent arrays of bytes, e.g.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000707to hold data read from a file.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000708\obindex{string}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000709\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}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000723\indexii{string}{comparison}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000724\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.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000735\obindex{tuple}
736\indexii{singleton}{tuple}
737\indexii{empty}{tuple}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000738
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.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000745\obindex{mutable sequece}
746\obindex{mutable}
747\indexii{assignment}{statement}
748\index{delete}
749\stindex{del}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000750\index{subscription}
751\index{slicing}
752
753There is currently a single mutable sequence type:
754
755\begin{description}
756
757\item[Lists]
758The elements of a list are arbitrary Python objects. Lists are formed
759by placing a comma-separated list of expressions in square brackets.
760(Note that there are no special cases needed to form lists of length 0
761or 1.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000762\obindex{list}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000763
764\end{description} % Mutable sequences
765
766\end{description} % Sequences
767
768\item[Mapping types]
769These represent finite sets of objects indexed by arbitrary index sets.
770The subscript notation \verb\a[k]\ selects the element indexed
771by \verb\k\ from the mapping \verb\a\; this can be used in
772expressions and as the target of assignments or \verb\del\ statements.
773The built-in function \verb\len()\ returns the number of elements
774in a mapping.
775\bifuncindex{len}
776\index{subscription}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000777\obindex{mapping}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000778
779There is currently a single mapping type:
780
781\begin{description}
782
783\item[Dictionaries]
784These represent finite sets of objects indexed by strings.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000785Dictionaries are mutable; they are created by the \verb\{...}\
786notation (see section \ref{dict}). (Implementation note: the strings
787used for indexing must not contain null bytes.)
788\obindex{dictionary}
789\obindex{mutable}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000790
791\end{description} % Mapping types
792
793\item[Callable types]
794These are the types to which the function call (invocation) operation,
795written as \verb\function(argument, argument, ...)\, can be applied:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000796\indexii{function}{call}
797\index{invocation}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000798\indexii{function}{argument}
799\obindex{callable}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000800
801\begin{description}
802
803\item[User-defined functions]
804A user-defined function object is created by a function definition
805(see section \ref{function}). It should be called with an argument
806list containing the same number of items as the function's formal
807parameter list.
808\indexii{user-defined}{function}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000809\obindex{function}
810\obindex{user-defined function}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000811
812Special read-only attributes: \verb\func_code\ is the code object
813representing the compiled function body, and \verb\func_globals\ is (a
814reference to) the dictionary that holds the function's global
815variables --- it implements the global name space of the module in
816which the function was defined.
817\ttindex{func_code}
818\ttindex{func_globals}
819\indexii{global}{name space}
820
821\item[User-defined methods]
Guido van Rossum60279da1992-04-02 10:24:59 +0000822A user-defined method (a.k.a. {\em object closure}) is a pair of a
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000823class instance object and a user-defined function. It should be
824called with an argument list containing one item less than the number
825of items in the function's formal parameter list. When called, the
826class instance becomes the first argument, and the call arguments are
827shifted one to the right.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000828\obindex{method}
829\obindex{user-defined method}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000830indexii{user-defined}{method}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000831\index{object closure}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000832
833Special read-only attributes: \verb\im_self\ is the class instance
834object, \verb\im_func\ is the function object.
835\ttindex{im_func}
836\ttindex{im_self}
837
838\item[Built-in functions]
839A built-in function object is a wrapper around a C function. Examples
840of built-in functions are \verb\len\ and \verb\math.sin\. There
841are no special attributes. The number and type of the arguments are
842determined by the C function.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000843\obindex{built-in function}
844\obindex{function}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000845\index{C}
846
847\item[Built-in methods]
848This is really a different disguise of a built-in function, this time
849containing an object passed to the C function as an implicit extra
850argument. An example of a built-in method is \verb\list.append\ if
851\verb\list\ is a list object.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000852\obindex{built-in method}
853\obindex{method}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000854\indexii{built-in}{method}
855
856\item[Classes]
857Class objects are described below. When a class object is called as a
858parameterless function, a new class instance (also described below) is
859created and returned. The class's initialization function is not
860called --- this is the responsibility of the caller. It is illegal to
861call a class object with one or more arguments.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000862\obindex{class}
863\obindex{class instance}
864\obindex{instance}
865\indexii{class object}{call}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000866
867\end{description}
868
869\item[Modules]
870Modules are imported by the \verb\import\ statement (see section
871\ref{import}). A module object is a container for a module's name
872space, which is a dictionary (the same dictionary as referenced by the
873\verb\func_globals\ attribute of functions defined in the module).
874Module attribute references are translated to lookups in this
875dictionary. A module object does not contain the code object used to
876initialize the module (since it isn't needed once the initialization
877is done).
878\stindex{import}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000879\obindex{module}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000880
881Attribute assignment update the module's name space dictionary.
882
883Special read-only attributes: \verb\__dict__\ yields the module's name
884space as a dictionary object; \verb\__name__\ yields the module's name
885as a string object.
886\ttindex{__dict__}
887\ttindex{__name__}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000888\indexii{module}{name space}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000889
890\item[Classes]
891Class objects are created by class definitions (see section
892\ref{class}). A class is a container for a dictionary containing the
893class's name space. Class attribute references are translated to
894lookups in this dictionary. When an attribute name is not found
895there, the attribute search continues in the base classes. The search
896is depth-first, left-to-right in the order of their occurrence in the
897base class list.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000898\obindex{class}
899\obindex{class instance}
900\obindex{instance}
901\indexii{class object}{call}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000902\index{container}
903\index{dictionary}
904\indexii{class}{attribute}
905
906Class attribute assignments update the class's dictionary, never the
907dictionary of a base class.
908\indexiii{class}{attribute}{assignment}
909
910A class can be called as a parameterless function to yield a class
911instance (see above).
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000912\indexii{class object}{call}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000913
914Special read-only attributes: \verb\__dict__\ yields te dictionary
915containing the class's name space; \verb\__bases__\ yields a tuple
916(possibly empty or a singleton) containing the base classes, in the
917order of their occurrence in the base class list.
918\ttindex{__dict__}
919\ttindex{__bases__}
920
921\item[Class instances]
922A class instance is created by calling a class object as a
923parameterless function. A class instance has a dictionary in which
924attribute references are searched. When an attribute is not found
925there, and the instance's class has an attribute by that name, and
926that class attribute is a user-defined function (and in no other
927cases), the instance attribute reference yields a user-defined method
928object (see above) constructed from the instance and the function.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000929\obindex{class instance}
930\obindex{instance}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000931\indexii{class}{instance}
932\indexii{class instance}{attribute}
933
934Attribute assignments update the instance's dictionary.
935\indexiii{class instance}{attribute}{assignment}
936
937Special read-only attributes: \verb\__dict__\ yields the attribute
938dictionary; \verb\__class__\ yields the instance's class.
939\ttindex{__dict__}
940\ttindex{__class__}
941
942\item[Files]
943A file object represents an open file. (It is a wrapper around a C
944{\tt stdio} file pointer.) File objects are created by the
945\verb\open()\ built-in function, and also by \verb\posix.popen()\ and
946the \verb\makefile\ method of socket objects. \verb\sys.stdin\,
947\verb\sys.stdout\ and \verb\sys.stderr\ are file objects corresponding
948the the interpreter's standard input, output and error streams.
949See the Python Library Reference for methods of file objects and other
950details.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000951\obindex{file}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000952\index{C}
953\index{stdio}
954\bifuncindex{open}
955\bifuncindex{popen}
956\bifuncindex{makefile}
957\ttindex{stdin}
958\ttindex{stdout}
959\ttindex{stderr}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000960\ttindex{sys.stdin}
961\ttindex{sys.stdout}
962\ttindex{sys.stderr}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000963
964\item[Internal types]
965A few types used internally by the interpreter are exposed to the user.
966Their definition may change with future versions of the interpreter,
967but they are mentioned here for completeness.
968\index{internal type}
969
970\begin{description}
971
972\item[Code objects]
973Code objects represent executable code. The difference between a code
974object and a function object is that the function object contains an
975explicit reference to the function's context (the module in which it
976was defined) which a code object contains no context. There is no way
977to execute a bare code object.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000978\obindex{code}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000979
980Special read-only attributes: \verb\co_code\ is a string representing
981the sequence of instructions; \verb\co_consts\ is a list of literals
982used by the code; \verb\co_names\ is a list of names (strings) used by
983the code; \verb\co_filename\ is the filename from which the code was
984compiled. (To find out the line numbers, you would have to decode the
985instructions; the standard library module \verb\dis\ contains an
986example of how to do this.)
987\ttindex{co_code}
988\ttindex{co_consts}
989\ttindex{co_names}
990\ttindex{co_filename}
991
992\item[Frame objects]
993Frame objects represent execution frames. They may occur in traceback
994objects (see below).
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000995\obindex{frame}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000996
997Special read-only attributes: \verb\f_back\ is to the previous
998stack frame (towards the caller), or \verb\None\ if this is the bottom
999stack frame; \verb\f_code\ is the code object being executed in this
1000frame; \verb\f_globals\ is the dictionary used to look up global
1001variables; \verb\f_locals\ is used for local variables;
1002\verb\f_lineno\ gives the line number and \verb\f_lasti\ gives the
1003precise instruction (this is an index into the instruction string of
1004the code object).
1005\ttindex{f_back}
1006\ttindex{f_code}
1007\ttindex{f_globals}
1008\ttindex{f_locals}
1009\ttindex{f_lineno}
1010\ttindex{f_lasti}
1011
1012\item[Traceback objects]
1013Traceback objects represent a stack trace of an exception. A
1014traceback object is created when an exception occurs. When the search
1015for an exception handler unwinds the execution stack, at each unwound
1016level a traceback object is inserted in front of the current
1017traceback. When an exception handler is entered, the stack trace is
1018made available to the program as \verb\sys.exc_traceback\. When the
1019program contains no suitable handler, the stack trace is written
1020(nicely formatted) to the standard error stream; if the interpreter is
1021interactive, it is also made available to the user as
1022\verb\sys.last_traceback\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001023\obindex{traceback}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001024\indexii{stack}{trace}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001025\indexii{exception}{handler}
1026\indexii{execution}{stack}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001027\ttindex{exc_traceback}
1028\ttindex{last_traceback}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001029\ttindex{sys.exc_traceback}
1030\ttindex{sys.last_traceback}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001031
1032Special read-only attributes: \verb\tb_next\ is the next level in the
1033stack trace (towards the frame where the exception occurred), or
1034\verb\None\ if there is no next level; \verb\tb_frame\ points to the
1035execution frame of the current level; \verb\tb_lineno\ gives the line
1036number where the exception occurred; \verb\tb_lasti\ indicates the
1037precise instruction. The line number and last instruction in the
1038traceback may differ from the line number of its frame object if the
1039exception occurred in a \verb\try\ statement with no matching
1040\verb\except\ clause or with a \verb\finally\ clause.
1041\ttindex{tb_next}
1042\ttindex{tb_frame}
1043\ttindex{tb_lineno}
1044\ttindex{tb_lasti}
1045\stindex{try}
1046
1047\end{description} % Internal types
1048
1049\end{description} % Types
1050
1051\chapter{Execution model}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001052\index{execution model}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001053
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001054\section{Code blocks, execution frames, and name spaces} \label{execframes}
1055\index{code block}
1056\indexii{execution}{frame}
1057\index{name space}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001058
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001059A {\em code block} is a piece of Python program text that can be
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001060executed as a unit, such as a module, a class definition or a function
1061body. Some code blocks (like modules) are executed only once, others
1062(like function bodies) may be executed many times. Code block may
1063textually contain other code blocks. Code blocks may invoke other
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001064code blocks (that may or may not be textually contained in them) as
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001065part of their execution, e.g. by invoking (calling) a function.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001066\index{code block}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001067\indexii{code}{block}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001068
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001069The following are code blocks: A module is a code block. A function
1070body is a code block. A class definition is a code block. Each
1071command typed interactively is a separate code block; a script file is
1072a code block. The string argument passed to the built-in functions
1073\verb\eval\ and \verb\exec\ are code blocks. And finally, the
1074expression read and evaluated by the built-in function \verb\input\ is
1075a code block.
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001076
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001077A code block is executed in an execution frame. An {\em execution
1078frame} contains some administrative information (used for debugging),
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001079determines where and how execution continues after the code block's
1080execution has completed, and (perhaps most importantly) defines two
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001081name spaces, the local and the global name space, that affect
1082execution of the code block.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001083\indexii{execution}{frame}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001084
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001085A {\em name space} is a mapping from names (identifiers) to objects.
1086A particular name space may be referenced by more than one execution
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001087frame, and from other places as well. Adding a name to a name space
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001088is called {\em binding} a name (to an object); changing the mapping of
1089a name is called {\em rebinding}; removing a name is {\em unbinding}.
1090Name spaces are functionally equivalent to dictionaries.
1091\index{name space}
1092\indexii{binding}{name}
1093\indexii{rebinding}{name}
1094\indexii{unbinding}{name}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001095
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001096The {\em local name space} of an execution frame determines the default
1097place where names are defined and searched. The {\em global name
1098space} determines the place where names listed in \verb\global\
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001099statements are defined and searched, and where names that are not
1100explicitly bound in the current code block are searched.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001101\indexii{local}{name space}
1102\indexii{global}{name space}
1103\stindex{global}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001104
1105Whether a name is local or global in a code block is determined by
1106static inspection of the source text for the code block: in the
1107absence of \verb\global\ statements, a name that is bound anywhere in
1108the code block is local in the entire code block; all other names are
1109considered global. The \verb\global\ statement forces global
1110interpretation of selected names throughout the code block. The
1111following constructs bind names: formal parameters, \verb\import\
1112statements, class and function definitions (these bind the class or
1113function name), and targets that are identifiers if occurring in an
1114assignment, \verb\for\ loop header, or \verb\except\ clause header.
1115(A target occurring in a \verb\del\ statement does not bind a name.)
1116
1117When a global name is not found in the global name space, it is
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001118searched in the list of ``built-in'' names (which is actually the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001119global name space of the module \verb\builtin\). When a name is not
1120found at all, the \verb\NameError\ exception is raised.
1121
1122The following table lists the meaning of the local and global name
1123space for various types of code blocks. The name space for a
1124particular module is automatically created when the module is first
1125referenced.
1126
1127\begin{center}
1128\begin{tabular}{|l|l|l|l|}
1129\hline
1130Code block type & Global name space & Local name space & Notes \\
1131\hline
1132Module & n.s. for this module & same as global & \\
1133Script & n.s. for \verb\__main__\ & same as global & \\
1134Interactive command & n.s. for \verb\__main__\ & same as global & \\
1135Class definition & global n.s. of containing block & new n.s. & \\
1136Function body & global n.s. of containing block & new n.s. & \\
1137String passed to \verb\exec\ or \verb\eval\
1138 & global n.s. of caller & local n.s. of caller & (1) \\
1139File read by \verb\execfile\
1140 & global n.s. of caller & local n.s. of caller & (1) \\
1141Expression read by \verb\input\
1142 & global n.s. of caller & local n.s. of caller & \\
1143\hline
1144\end{tabular}
1145\end{center}
1146
1147Notes:
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001148
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001149\begin{description}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001150
1151\item[n.s.] means {\em name space}
1152
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001153\item[(1)] The global and local name space for these functions can be
1154overridden with optional extra arguments.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001155
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001156\end{description}
1157
1158\section{Exceptions}
1159
1160Exceptions are a means of breaking out of the normal flow of control
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001161of a code block in order to handle errors or other exceptional
1162conditions. An exception is {\em raised} at the point where the error
1163is detected; it may be {\em handled} by the surrounding code block or
1164by any code block that directly or indirectly invoked the code block
1165where the error occurred.
1166\index{exception}
1167\index{raise an exception}
1168\index{handle an exception}
1169\index{exception handler}
1170\index{errors}
1171\index{error handling}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001172
1173The Python interpreter raises an exception when it detects an run-time
1174error (such as division by zero). A Python program can also
1175explicitly raise an exception with the \verb\raise\ statement.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001176Exception handlers are specified with the \verb\try...except\
1177statement.
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001178
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001179Python uses the ``termination'' model of error handling: an exception
1180handler can find out what happened and continue execution at an outer
1181level, but it cannot repair the cause of the error and retry the
1182failing operation (except by re-entering the the offending piece of
1183code from the top).
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001184
1185When an exception is not handled at all, the interpreter terminates
1186execution of the program, or returns to its interactive main loop.
1187
1188Exceptions are identified by string objects. Two different string
1189objects with the same value identify different exceptions.
1190
1191When an exception is raised, an object (maybe \verb\None\) is passed
1192as the exception's ``parameter''; this object does not affect the
1193selection of an exception handler, but is passed to the selected
1194exception handler as additional information.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001195
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001196See also the description of the \verb\try\ and \verb\raise\
1197statements.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001198
Guido van Rossumf2612d11991-11-21 13:53:03 +00001199\chapter{Expressions and conditions}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001200\index{expression}
1201\index{condition}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001202
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001203{\bf Note:} In this and the following chapters, extended BNF notation
1204will be used to describe syntax, not lexical analysis.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001205\index{BNF}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001206
1207This chapter explains the meaning of the elements of expressions and
1208conditions. Conditions are a superset of expressions, and a condition
Guido van Rossum670e5a01992-01-17 14:03:20 +00001209may be used wherever an expression is required by enclosing it in
1210parentheses. The only places where expressions are used in the syntax
1211instead of conditions is in expression statements and on the
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001212right-hand side of assignment statements; this catches some nasty bugs
1213like accedentally writing \verb\x == 1\ instead of \verb\x = 1\.
1214\indexii{assignment}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001215
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001216The comma plays several roles in Python's syntax. It is usually an
Guido van Rossum743d1e71992-01-07 16:43:53 +00001217operator with a lower precedence than all others, but occasionally
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001218serves other purposes as well; e.g. it separates function arguments,
Guido van Rossum670e5a01992-01-17 14:03:20 +00001219is used in list and dictionary constructors, and has special semantics
1220in \verb\print\ statements.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001221\index{comma}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001222
1223When (one alternative of) a syntax rule has the form
1224
1225\begin{verbatim}
1226name: othername
1227\end{verbatim}
1228
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001229and no semantics are given, the semantics of this form of \verb\name\
1230are the same as for \verb\othername\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001231\index{syntax}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001232
1233\section{Arithmetic conversions}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001234\indexii{arithmetic}{conversion}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001235
1236When a description of an arithmetic operator below uses the phrase
1237``the numeric arguments are converted to a common type'',
1238this both means that if either argument is not a number, a
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001239\verb\TypeError\ exception is raised, and that otherwise
Guido van Rossumf2612d11991-11-21 13:53:03 +00001240the following conversions are applied:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001241\exindex{TypeError}
1242\indexii{floating point}{number}
1243\indexii{long}{integer}
1244\indexii{plain}{integer}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001245
1246\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001247\item first, if either argument is a floating point number,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001248 the other is converted to floating point;
1249\item else, if either argument is a long integer,
1250 the other is converted to long integer;
Guido van Rossum670e5a01992-01-17 14:03:20 +00001251\item otherwise, both must be plain integers and no conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +00001252 is necessary.
1253\end{itemize}
1254
Guido van Rossumf2612d11991-11-21 13:53:03 +00001255\section{Atoms}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001256\index{atom}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001257
Guido van Rossum670e5a01992-01-17 14:03:20 +00001258Atoms are the most basic elements of expressions. Forms enclosed in
1259reverse quotes or in parentheses, brackets or braces are also
1260categorized syntactically as atoms. The syntax for atoms is:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001261
1262\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001263atom: identifier | literal | enclosure
1264enclosure: parenth_form | list_display | dict_display | string_conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +00001265\end{verbatim}
1266
1267\subsection{Identifiers (Names)}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001268\index{name}
1269\index{identifier}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001270
1271An identifier occurring as an atom is a reference to a local, global
Guido van Rossum670e5a01992-01-17 14:03:20 +00001272or built-in name binding. If a name can be assigned to anywhere in a
1273code block, and is not mentioned in a \verb\global\ statement in that
1274code block, it refers to a local name throughout that code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001275Otherwise, it refers to a global name if one exists, else to a
1276built-in name.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001277\indexii{name}{binding}
1278\index{code block}
1279\stindex{global}
1280\indexii{built-in}{name}
1281\indexii{global}{name}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001282
Guido van Rossum670e5a01992-01-17 14:03:20 +00001283When the name is bound to an object, evaluation of the atom yields
1284that object. When a name is not bound, an attempt to evaluate it
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001285raises a \verb\NameError\ exception.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001286\exindex{NameError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001287
1288\subsection{Literals}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001289\index{literal}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001290
Guido van Rossum670e5a01992-01-17 14:03:20 +00001291Python knows string and numeric literals:
1292
1293\begin{verbatim}
1294literal: stringliteral | integer | longinteger | floatnumber
1295\end{verbatim}
1296
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001297Evaluation of a literal yields an object of the given type (string,
1298integer, long integer, floating point number) with the given value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001299The value may be approximated in the case of floating point literals.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001300See section \ref{literals} for details.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001301
Guido van Rossum670e5a01992-01-17 14:03:20 +00001302All literals correspond to immutable data types, and hence the
1303object's identity is less important than its value. Multiple
1304evaluations of literals with the same value (either the same
1305occurrence in the program text or a different occurrence) may obtain
1306the same object or a different object with the same value.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001307\indexiii{immutable}{data}{type}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001308
1309(In the original implementation, all literals in the same code block
1310with the same type and value yield the same object.)
1311
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001312\subsection{Parenthesized forms}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001313\index{parenthesized form}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001314
Guido van Rossum670e5a01992-01-17 14:03:20 +00001315A parenthesized form is an optional condition list enclosed in
1316parentheses:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001317
Guido van Rossum670e5a01992-01-17 14:03:20 +00001318\begin{verbatim}
1319parenth_form: "(" [condition_list] ")"
1320\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001321
Guido van Rossum670e5a01992-01-17 14:03:20 +00001322A parenthesized condition list yields whatever that condition list
1323yields.
1324
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001325An empty pair of parentheses yields an empty tuple object. Since
1326tuples are immutable, the rules for literals apply here.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001327\indexii{empty}{tuple}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001328
1329(Note that tuples are not formed by the parentheses, but rather by use
1330of the comma operator. The exception is the empty tuple, for which
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001331parentheses {\em are} required --- allowing unparenthesized ``nothing''
Guido van Rossum670e5a01992-01-17 14:03:20 +00001332in expressions would causes ambiguities and allow common typos to
1333pass uncaught.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001334\index{comma}
1335\index{tuple}{display}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001336
1337\subsection{List displays}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001338\indexii{list}{display}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001339
Guido van Rossum670e5a01992-01-17 14:03:20 +00001340A list display is a possibly empty series of conditions enclosed in
1341square brackets:
1342
1343\begin{verbatim}
1344list_display: "[" [condition_list] "]"
1345\end{verbatim}
1346
Guido van Rossumf2612d11991-11-21 13:53:03 +00001347A list display yields a new list object.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001348\obindex{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001349
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001350If it has no condition list, the list object has no items. Otherwise,
1351the elements of the condition list are evaluated from left to right
1352and inserted in the list object in that order.
1353\indexii{empty}{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001354
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001355\subsection{Dictionary displays} \label{dict}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001356\indexii{dictionary}{display}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001357
Guido van Rossum670e5a01992-01-17 14:03:20 +00001358A dictionary display is a possibly empty series of key/datum pairs
1359enclosed in curly braces:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001360\index{key}
1361\index{datum}
1362\index{key/datum pair}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001363
1364\begin{verbatim}
1365dict_display: "{" [key_datum_list] "}"
1366key_datum_list: [key_datum ("," key_datum)* [","]
1367key_datum: condition ":" condition
1368\end{verbatim}
1369
Guido van Rossumf2612d11991-11-21 13:53:03 +00001370A dictionary display yields a new dictionary object.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001371\obindex{dictionary}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001372
Guido van Rossum670e5a01992-01-17 14:03:20 +00001373The key/datum pairs are evaluated from left to right to define the
1374entries of the dictionary: each key object is used as a key into the
1375dictionary to store the corresponding datum.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001376
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001377Keys must be strings, otherwise a \verb\TypeError\ exception is
1378raised. Clashes between duplicate keys are not detected; the last
1379datum (textually rightmost in the display) stored for a given key
1380value prevails.
1381\exindex{TypeError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001382
1383\subsection{String conversions}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001384\indexii{string}{conversion}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001385
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001386A string conversion is a condition list enclosed in reverse (or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001387backward) quotes:
1388
1389\begin{verbatim}
1390string_conversion: "`" condition_list "`"
1391\end{verbatim}
1392
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001393A string conversion evaluates the contained condition list and
1394converts the resulting object into a string according to rules
1395specific to its type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001396
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001397If the object is a string, a number, \verb\None\, or a tuple, list or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001398dictionary containing only objects whose type is one of these, the
1399resulting string is a valid Python expression which can be passed to
1400the built-in function \verb\eval()\ to yield an expression with the
Guido van Rossumf2612d11991-11-21 13:53:03 +00001401same value (or an approximation, if floating point numbers are
1402involved).
1403
1404(In particular, converting a string adds quotes around it and converts
1405``funny'' characters to escape sequences that are safe to print.)
1406
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001407It is illegal to attempt to convert recursive objects (e.g. lists or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001408dictionaries that contain a reference to themselves, directly or
1409indirectly.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001410\obindex{recursive}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001411
Guido van Rossum60279da1992-04-02 10:24:59 +00001412\section{Primaries} \label{primaries}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001413\index{primary}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001414
1415Primaries represent the most tightly bound operations of the language.
1416Their syntax is:
1417
1418\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001419primary: atom | attributeref | subscription | slicing | call
Guido van Rossumf2612d11991-11-21 13:53:03 +00001420\end{verbatim}
1421
1422\subsection{Attribute references}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001423\indexii{attribute}{reference}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001424
Guido van Rossum670e5a01992-01-17 14:03:20 +00001425An attribute reference is a primary followed by a period and a name:
1426
1427\begin{verbatim}
1428attributeref: primary "." identifier
1429\end{verbatim}
1430
1431The primary must evaluate to an object of a type that supports
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001432attribute references, e.g. a module or a list. This object is then
Guido van Rossum670e5a01992-01-17 14:03:20 +00001433asked to produce the attribute whose name is the identifier. If this
1434attribute is not available, the exception \verb\AttributeError\ is
1435raised. Otherwise, the type and value of the object produced is
1436determined by the object. Multiple evaluations of the same attribute
1437reference may yield different objects.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001438\obindex{module}
1439\obindex{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001440
1441\subsection{Subscriptions}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001442\index{subscription}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001443
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001444A subscription selects an item of a sequence (string, tuple or list)
1445or mapping (dictionary) object:
1446\obindex{sequence}
1447\obindex{mapping}
1448\obindex{string}
1449\obindex{tuple}
1450\obindex{list}
1451\obindex{dictionary}
1452\indexii{sequence}{item}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001453
1454\begin{verbatim}
1455subscription: primary "[" condition "]"
1456\end{verbatim}
1457
1458The primary must evaluate to an object of a sequence or mapping type.
1459
1460If it is a mapping, the condition must evaluate to an object whose
1461value is one of the keys of the mapping, and the subscription selects
1462the value in the mapping that corresponds to that key.
1463
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001464If it is a sequence, the condition must evaluate to a plain integer.
1465If this value is negative, the length of the sequence is added to it
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001466(so that, e.g. \verb\x[-1]\ selects the last item of \verb\x\.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001467The resulting value must be a nonnegative integer smaller than the
1468number of items in the sequence, and the subscription selects the item
1469whose index is that value (counting from zero).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001470
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001471A string's items are characters. A character is not a separate data
Guido van Rossum670e5a01992-01-17 14:03:20 +00001472type but a string of exactly one character.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001473\index{character}
1474\indexii{string}{item}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001475
Guido van Rossumf2612d11991-11-21 13:53:03 +00001476\subsection{Slicings}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001477\index{slicing}
1478\index{slice}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001479
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001480A slicing (or slice) selects a range of items in a sequence (string,
1481tuple or list) object:
1482\obindex{sequence}
1483\obindex{string}
1484\obindex{tuple}
1485\obindex{list}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001486
1487\begin{verbatim}
1488slicing: primary "[" [condition] ":" [condition] "]"
1489\end{verbatim}
1490
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001491The primary must evaluate to a sequence object. The lower and upper
1492bound expressions, if present, must evaluate to plain integers;
1493defaults are zero and the sequence's length, respectively. If either
1494bound is negative, the sequence's length is added to it. The slicing
1495now selects all items with index $k$ such that $i <= k < j$ where $i$
1496and $j$ are the specified lower and upper bounds. This may be an
1497empty sequence. It is not an error if $i$ or $j$ lie outside the
1498range of valid indexes (such items don't exist so they aren't
1499selected).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001500
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001501\subsection{Calls} \label{calls}
1502\index{call}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001503
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001504A call calls a callable object (e.g. a function) with a possibly empty
1505series of arguments:
1506\obindex{callable}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001507
1508\begin{verbatim}
1509call: primary "(" [condition_list] ")"
1510\end{verbatim}
1511
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001512The primary must evaluate to a callable object (user-defined
1513functions, built-in functions, methods of built-in objects, class
1514objects, and methods of class instances are callable). If it is a
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001515class, the argument list must be empty; otherwise, the arguments are
1516evaluated.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001517
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001518A call always returns some value, possibly \verb\None\, unless it
1519raises an exception. How this value is computed depends on the type
1520of the callable object. If it is:
1521
1522\begin{description}
1523
1524\item[a user-defined function:] the code block for the function is
1525executed, passing it the argument list. The first thing the code
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001526block will do is bind the formal parameters to the arguments; this is
1527described in section \ref{function}. When the code block executes a
1528\verb\return\ statement, this specifies the return value of the
1529function call.
1530\indexii{function}{call}
1531\indexiii{user-defined}{function}{call}
1532\obindex{user-defined function}
1533\obindex{function}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001534
1535\item[a built-in function or method:] the result is up to the
1536interpreter; see the library reference manual for the descriptions of
1537built-in functions and methods.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001538\indexii{function}{call}
1539\indexii{built-in function}{call}
1540\indexii{method}{call}
1541\indexii{built-in method}{call}
1542\obindex{built-in method}
1543\obindex{built-in function}
1544\obindex{method}
1545\obindex{function}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001546
1547\item[a class object:] a new instance of that class is returned.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001548\obindex{class}
1549\indexii{class object}{call}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001550
1551\item[a class instance method:] the corresponding user-defined
1552function is called, with an argument list that is one longer than the
1553argument list of the call: the instance becomes the first argument.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001554\obindex{class instance}
1555\obindex{instance}
1556\indexii{instance}{call}
1557\indexii{class instance}{call}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001558
1559\end{description}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001560
Guido van Rossum60279da1992-04-02 10:24:59 +00001561\section{Unary arithmetic operations}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001562\indexiii{unary}{arithmetic}{operation}
1563\indexiii{unary}{bit-wise}{operation}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001564
Guido van Rossum60279da1992-04-02 10:24:59 +00001565All unary arithmetic (and bit-wise) operations have the same priority:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001566
1567\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001568u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001569\end{verbatim}
1570
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001571The unary \verb\"-"\ (minus) operator yields the negation of its
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001572numeric argument.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001573\index{negation}
1574\index{minus}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001575
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001576The unary \verb\"+"\ (plus) operator yields its numeric argument
1577unchanged.
1578\index{plus}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001579
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001580The unary \verb\"~"\ (invert) operator yields the bit-wise inversion
1581of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001582\verb\x\ is defined as \verb\-(x+1)\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001583\index{inversion}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001584
1585In all three cases, if the argument does not have the proper type,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001586a \verb\TypeError\ exception is raised.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001587\exindex{TypeError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001588
Guido van Rossum60279da1992-04-02 10:24:59 +00001589\section{Binary arithmetic operations}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001590\indexiii{binary}{arithmetic}{operation}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001591
Guido van Rossum60279da1992-04-02 10:24:59 +00001592The binary arithmetic operations have the conventional priority
1593levels. Note that some of these operations also apply to certain
1594non-numeric types. There is no ``power'' operator, so there are only
1595two levels, one for multiplicative operators and one for additive
1596operators:
1597
Guido van Rossumf2612d11991-11-21 13:53:03 +00001598\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001599m_expr: u_expr | m_expr "*" u_expr | m_expr "/" u_expr | m_expr "%" u_expr
1600a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001601\end{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001602
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001603The \verb\"*"\ (multiplication) operator yields the product of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001604arguments. The arguments must either both be numbers, or one argument
1605must be a plain integer and the other must be a sequence. In the
1606former case, the numbers are converted to a common type and then
1607multiplied together. In the latter case, sequence repetition is
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001608performed; a negative repetition factor yields an empty sequence.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001609\index{multiplication}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001610
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001611The \verb\"/"\ (division) operator yields the quotient of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001612arguments. The numeric arguments are first converted to a common
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001613type. Plain or long integer division yields an integer of the same
1614type; the result is that of mathematical division with the `floor'
1615function applied to the result. Division by zero raises the
1616\verb\ZeroDivisionError\ exception.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001617\exindex{ZeroDivisionError}
1618\index{division}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001619
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001620The \verb\"%"\ (modulo) operator yields the remainder from the
Guido van Rossum670e5a01992-01-17 14:03:20 +00001621division of the first argument by the second. The numeric arguments
Guido van Rossum60279da1992-04-02 10:24:59 +00001622are first converted to a common type. A zero right argument raises
1623the \verb\ZeroDivisionError\ exception. The arguments may be floating
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001624point numbers, e.g. \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo
Guido van Rossum60279da1992-04-02 10:24:59 +00001625operator always yields a result with the same sign as its second
1626operand (or zero); the absolute value of the result is strictly
1627smaller than the second operand.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001628\index{modulo}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001629
1630The integer division and modulo operators are connected by the
Guido van Rossum60279da1992-04-02 10:24:59 +00001631following identity: \verb\x == (x/y)*y + (x%y)\. Integer division and
1632modulo are also connected with the built-in function \verb\divmod()\:
1633\verb\divmod(x, y) == (x/y, x%y)\. These identities don't hold for
1634floating point numbers; there a similar identity holds where
1635\verb\x/y\ is replaced by \verb\floor(x/y)\).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001636
Guido van Rossum60279da1992-04-02 10:24:59 +00001637The \verb\"+"\ (addition) operator yields the sum of its arguments.
1638The arguments must either both be numbers, or both sequences of the
1639same type. In the former case, the numbers are converted to a common
1640type and then added together. In the latter case, the sequences are
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001641concatenated.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001642\index{addition}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001643
Guido van Rossum60279da1992-04-02 10:24:59 +00001644The \verb\"-"\ (subtraction) operator yields the difference of its
1645arguments. The numeric arguments are first converted to a common
1646type.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001647\index{subtraction}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001648
Guido van Rossum60279da1992-04-02 10:24:59 +00001649\section{Shifting operations}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001650\indexii{shifting}{operation}
Guido van Rossum60279da1992-04-02 10:24:59 +00001651
1652The shifting operations have lower priority than the arithmetic
1653operations:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001654
1655\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001656shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001657\end{verbatim}
1658
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001659These operators accept plain or long integers as arguments. The
1660arguments are converted to a common type. They shift the first
1661argument to the left or right by the number of bits given by the
1662second argument.
1663
1664A right shift by $n$ bits is defined as division by $2^n$. A left
Guido van Rossum60279da1992-04-02 10:24:59 +00001665shift by $n$ bits is defined as multiplication with $2^n$; for plain
1666integers there is no overflow check so this drops bits and flip the
1667sign if the result is not less than $2^{31}$ in absolute value.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001668
1669Negative shift counts raise a \verb\ValueError\ exception.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001670\exindex{ValueError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001671
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001672\section{Binary bit-wise operations}
1673\indexiii{binary}{bit-wise}{operation}
Guido van Rossum60279da1992-04-02 10:24:59 +00001674
1675Each of the three bitwise operations has a different priority level:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001676
1677\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001678and_expr: shift_expr | and_expr "&" shift_expr
Guido van Rossum743d1e71992-01-07 16:43:53 +00001679xor_expr: and_expr | xor_expr "^" and_expr
Guido van Rossum743d1e71992-01-07 16:43:53 +00001680or_expr: xor_expr | or_expr "|" xor_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001681\end{verbatim}
1682
Guido van Rossum60279da1992-04-02 10:24:59 +00001683The \verb\"&"\ operator yields the bitwise AND of its arguments, which
1684must be plain or long integers. The arguments are converted to a
1685common type.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001686\indexii{bit-wise}{and}
Guido van Rossum60279da1992-04-02 10:24:59 +00001687
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001688The \verb\"^"\ operator yields the bitwise XOR (exclusive OR) of its
Guido van Rossum60279da1992-04-02 10:24:59 +00001689arguments, which must be plain or long integers. The arguments are
1690converted to a common type.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001691\indexii{bit-wise}{xor}
1692\indexii{exclusive}{or}
Guido van Rossum60279da1992-04-02 10:24:59 +00001693
1694The \verb\"|"\ operator yields the bitwise (inclusive) OR of its
1695arguments, which must be plain or long integers. The arguments are
1696converted to a common type.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001697\indexii{bit-wise}{or}
1698\indexii{inclusive}{or}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001699
1700\section{Comparisons}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001701\index{comparison}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001702
Guido van Rossum60279da1992-04-02 10:24:59 +00001703Contrary to C, all comparison operations in Python have the same
1704priority, which is lower than that of any arithmetic, shifting or
1705bitwise operation. Also contrary to C, expressions like
1706\verb\a < b < c\ have the interpretation that is conventional in
1707mathematics:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001708\index{C}
Guido van Rossum60279da1992-04-02 10:24:59 +00001709
Guido van Rossumf2612d11991-11-21 13:53:03 +00001710\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001711comparison: or_expr (comp_operator or_expr)*
Guido van Rossum743d1e71992-01-07 16:43:53 +00001712comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001713\end{verbatim}
1714
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001715Comparisons yield integer values: 1 for true, 0 for false.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001716
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001717Comparisons can be chained arbitrarily, e.g. $x < y <= z$ is
1718equivalent to $x < y$ \verb\and\ $y <= z$, except that $y$ is
1719evaluated only once (but in both cases $z$ is not evaluated at all
1720when $x < y$ is found to be false).
1721\indexii{chaining}{comparisons}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001722
1723Formally, $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 +00001724$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 +00001725$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
1726
1727Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001728between $e_0$ and $e_2$, e.g. $x < y > z$ is perfectly legal.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001729
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001730The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with
1731C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below
1732\verb\<>\ is also implied.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001733
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001734The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
Guido van Rossumf2612d11991-11-21 13:53:03 +00001735the values of two objects. The objects needn't have the same type.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001736If both are numbers, they are coverted to a common type. Otherwise,
1737objects of different types {\em always} compare unequal, and are
1738ordered consistently but arbitrarily.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001739
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001740(This unusual definition of comparison is done to simplify the
1741definition of operations like sorting and the \verb\in\ and \verb\not
1742in\ operators.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001743
1744Comparison of objects of the same type depends on the type:
1745
1746\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001747
1748\item
1749Numbers are compared arithmetically.
1750
1751\item
1752Strings are compared lexicographically using the numeric equivalents
1753(the result of the built-in function \verb\ord\) of their characters.
1754
1755\item
1756Tuples and lists are compared lexicographically using comparison of
1757corresponding items.
1758
1759\item
1760Mappings (dictionaries) are compared through lexicographic
1761comparison of their sorted (key, value) lists.%
1762\footnote{This is expensive since it requires sorting the keys first,
1763but about the only sensible definition. It was tried to compare
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00001764dictionaries by identity only, but this caused surprises because
1765people expected to be able to test a dictionary for emptiness by
1766comparing it to {\tt \{\}}.}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001767
1768\item
1769Most other types compare unequal unless they are the same object;
1770the choice whether one object is considered smaller or larger than
1771another one is made arbitrarily but consistently within one
1772execution of a program.
1773
Guido van Rossumf2612d11991-11-21 13:53:03 +00001774\end{itemize}
1775
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001776The operators \verb\in\ and \verb\not in\ test for sequence
1777membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and
1778only if there exists an index $i$ such that $x = y[i]$.
1779$x ~\verb\not in\~ y$ yields the inverse truth value. The exception
1780\verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is
1781a string and $x$ is not a string of length one.%
1782\footnote{The latter restriction is sometimes a nuisance.}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001783\opindex{in}
1784\opindex{not in}
1785\indexii{membership}{test}
1786\obindex{sequence}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001787
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001788The operators \verb\is\ and \verb\is not\ test for object identity:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001789$x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same
1790object. $x ~\verb\is not\~ y$ yields the inverse truth value.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001791\opindex{is}
1792\opindex{is not}
1793\indexii{identity}{test}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001794
Guido van Rossum60279da1992-04-02 10:24:59 +00001795\section{Boolean operations} \label{Booleans}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001796\indexii{Boolean}{operation}
Guido van Rossum60279da1992-04-02 10:24:59 +00001797
1798Boolean operations have the lowest priority of all Python operations:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001799
1800\begin{verbatim}
1801condition: or_test
Guido van Rossum743d1e71992-01-07 16:43:53 +00001802or_test: and_test | or_test "or" and_test
1803and_test: not_test | and_test "and" not_test
1804not_test: comparison | "not" not_test
Guido van Rossumf2612d11991-11-21 13:53:03 +00001805\end{verbatim}
1806
Guido van Rossum60279da1992-04-02 10:24:59 +00001807In the context of Boolean operations, and also when conditions are
1808used by control flow statements, the following values are interpreted
1809as false: \verb\None\, numeric zero of all types, empty sequences
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001810(strings, tuples and lists), and empty mappings (dictionaries). All
1811other values are interpreted as true.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001812
1813The operator \verb\not\ yields 1 if its argument is false, 0 otherwise.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001814\opindex{not}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001815
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001816The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false,
Guido van Rossum60279da1992-04-02 10:24:59 +00001817its value is returned; otherwise, $y$ is evaluated and the resulting
1818value is returned.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001819\opindex{and}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001820
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001821The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true,
Guido van Rossum60279da1992-04-02 10:24:59 +00001822its value is returned; otherwise, $y$ is evaluated and the resulting
1823value is returned.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001824\opindex{or}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001825
1826(Note that \verb\and\ and \verb\or\ do not restrict the value and type
1827they return to 0 and 1, but rather return the last evaluated argument.
Guido van Rossum60279da1992-04-02 10:24:59 +00001828This is sometimes useful, e.g. if \verb\s\ is a string that should be
1829replaced by a default value if it is empty, the expression
1830\verb\s or 'foo'\ yields the desired value. Because \verb\not\ has to
1831invent a value anyway, it does not bother to return a value of the
1832same type as its argument, so e.g. \verb\not 'foo'\ yields \verb\0\,
1833not \verb\''\.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001834
1835\section{Expression lists and condition lists}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001836\indexii{expression}{list}
1837\indexii{condition}{list}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001838
1839\begin{verbatim}
1840expr_list: or_expr ("," or_expr)* [","]
1841cond_list: condition ("," condition)* [","]
1842\end{verbatim}
1843
1844The only difference between expression lists and condition lists is
1845the lowest priority of operators that can be used in them without
1846being enclosed in parentheses; condition lists allow all operators,
1847while expression lists don't allow comparisons and Boolean operators
1848(they do allow bitwise and shift operators though).
1849
1850Expression lists are used in expression statements and assignments;
Guido van Rossum60279da1992-04-02 10:24:59 +00001851condition lists are used everywhere else where a list of
1852comma-separated values is required.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001853
1854An expression (condition) list containing at least one comma yields a
1855tuple. The length of the tuple is the number of expressions
1856(conditions) in the list. The expressions (conditions) are evaluated
Guido van Rossum60279da1992-04-02 10:24:59 +00001857from left to right. (Conditions lists are used syntactically is a few
1858places where no tuple is constructed but a list of values is needed
1859nevertheless.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001860\obindex{tuple}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001861
1862The trailing comma is required only to create a single tuple (a.k.a. a
1863{\em singleton}); it is optional in all other cases. A single
1864expression (condition) without a trailing comma doesn't create a
1865tuple, but rather yields the value of that expression (condition).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001866\indexii{trailing}{comma}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001867
Guido van Rossum60279da1992-04-02 10:24:59 +00001868(To create an empty tuple, use an empty pair of parentheses:
1869\verb\()\.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001870
1871\chapter{Simple statements}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001872\indexii{simple}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001873
1874Simple statements are comprised within a single logical line.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001875Several simple statements may occur on a single line separated
Guido van Rossumf2612d11991-11-21 13:53:03 +00001876by semicolons. The syntax for simple statements is:
1877
1878\begin{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001879simple_stmt: expression_stmt
Guido van Rossum60279da1992-04-02 10:24:59 +00001880 | assignment_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001881 | pass_stmt
1882 | del_stmt
1883 | print_stmt
1884 | return_stmt
1885 | raise_stmt
1886 | break_stmt
1887 | continue_stmt
1888 | import_stmt
Guido van Rossum743d1e71992-01-07 16:43:53 +00001889 | global_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001890\end{verbatim}
1891
1892\section{Expression statements}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001893\indexii{expression}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001894
Guido van Rossum60279da1992-04-02 10:24:59 +00001895Expression statements are used (mostly interactively) to compute and
1896write a value, or (usually) to call a procedure (a function that
1897returns no meaningful result; in Python, procedures return the value
1898\verb\None\):
1899
Guido van Rossumf2612d11991-11-21 13:53:03 +00001900\begin{verbatim}
1901expression_stmt: expression_list
1902\end{verbatim}
1903
Guido van Rossum60279da1992-04-02 10:24:59 +00001904An expression statement evaluates the expression list (which may be a
1905single expression). If the value is not \verb\None\, it is converted
1906to a string using the rules for string conversions (expressions in
1907reverse quotes), and the resulting string is written to standard
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001908output (see section \ref{print}) on a line by itself.
1909\indexii{expression}{list}
1910\ttindex{None}
1911\indexii{string}{conversion}
1912\index{output}
1913\indexii{standard}{output}
1914\indexii{writing}{values}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001915
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001916(The exception for \verb\None\ is made so that procedure calls, which
1917are syntactically equivalent to expressions, do not cause any output.
1918A tuple with only \verb\None\ items is written normally.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001919\indexii{procedure}{call}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001920
Guido van Rossum60279da1992-04-02 10:24:59 +00001921\section{Assignment statements}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001922\indexii{assignment}{statement}
Guido van Rossum60279da1992-04-02 10:24:59 +00001923
1924Assignment statements are used to (re)bind names to values and to
1925modify attributes or items of mutable objects:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001926\indexii{binding}{name}
1927\indexii{rebinding}{name}
1928\obindex{mutable}
1929\indexii{attribute}{assignment}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001930
1931\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001932assignment_stmt: (target_list "=")+ expression_list
1933target_list: target ("," target)* [","]
1934target: identifier | "(" target_list ")" | "[" target_list "]"
1935 | attributeref | subscription | slicing
Guido van Rossumf2612d11991-11-21 13:53:03 +00001936\end{verbatim}
1937
Guido van Rossum60279da1992-04-02 10:24:59 +00001938(See section \ref{primaries} for the syntax definitions for the last
Guido van Rossumf2612d11991-11-21 13:53:03 +00001939three symbols.)
1940
Guido van Rossum60279da1992-04-02 10:24:59 +00001941An assignment statement evaluates the expression list (remember that
1942this can be a single expression or a comma-separated list, the latter
1943yielding a tuple) and assigns the single resulting object to each of
1944the target lists, from left to right.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001945\indexii{expression}{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001946
Guido van Rossum60279da1992-04-02 10:24:59 +00001947Assignment is defined recursively depending on the form of the target
1948(list). When a target is part of a mutable object (an attribute
1949reference, subscription or slicing), the mutable object must
1950ultimately perform the assignment and decide about its validity, and
1951may raise an exception if the assignment is unacceptable. The rules
1952observed by various types and the exceptions raised are given with the
1953definition of the object types (see section \ref{types}).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001954\index{target}
1955\indexii{target}{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001956
Guido van Rossum60279da1992-04-02 10:24:59 +00001957Assignment of an object to a target list is recursively defined as
1958follows.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001959\indexiii{target}{list}{assignment}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001960
1961\begin{itemize}
1962\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001963If the target list is a single target: the object is assigned to that
1964target.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001965
1966\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001967If the target list is a comma-separated list of targets: the object
1968must be a tuple with the same number of items as the list contains
1969targets, and the items are assigned, from left to right, to the
1970corresponding targets.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001971
1972\end{itemize}
1973
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001974Assignment of an object to a single target is recursively defined as
Guido van Rossum60279da1992-04-02 10:24:59 +00001975follows.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001976
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001977\begin{itemize} % nested
Guido van Rossumf2612d11991-11-21 13:53:03 +00001978
1979\item
1980If the target is an identifier (name):
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001981
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001982\begin{itemize}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001983
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001984\item
1985If the name does not occur in a \verb\global\ statement in the current
Guido van Rossum60279da1992-04-02 10:24:59 +00001986code block: the name is bound to the object in the current local name
1987space.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001988\stindex{global}
1989
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001990\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001991Otherwise: the name is bound to the object in the current global name
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001992space.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001993
1994\end{itemize} % nested
1995
Guido van Rossum60279da1992-04-02 10:24:59 +00001996The name is rebound if it was already bound.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001997
1998\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001999If the target is a target list enclosed in parentheses: the object is
2000assigned to that target list as described above.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002001
2002\item
Guido van Rossum60279da1992-04-02 10:24:59 +00002003If the target is a target list enclosed in square brackets: the object
2004must be a list with the same number of items as the target list
2005contains targets, and its items are assigned, from left to right, to
2006the corresponding targets.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002007
2008\item
Guido van Rossum60279da1992-04-02 10:24:59 +00002009If the target is an attribute reference: The primary expression in the
2010reference is evaluated. It should yield an object with assignable
2011attributes; if this is not the case, \verb\TypeError\ is raised. That
2012object is then asked to assign the assigned object to the given
2013attribute; if it cannot perform the assignment, it raises an exception
2014(usually but not necessarily \verb\AttributeError\).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002015\indexii{attribute}{assignment}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002016
2017\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002018If the target is a subscription: The primary expression in the
2019reference is evaluated. It should yield either a mutable sequence
2020(list) object or a mapping (dictionary) object. Next, the subscript
2021expression is evaluated.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002022\indexii{subscription}{assignment}
2023\obindex{mutable}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002024
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002025If the primary is a mutable sequence object (a list), the subscript
2026must yield a plain integer. If it is negative, the sequence's length
2027is added to it. The resulting value must be a nonnegative integer
2028less than the sequence's length, and the sequence is asked to assign
2029the assigned object to its item with that index. If the index is out
2030of range, \verb\IndexError\ is raised (assignment to a subscripted
2031sequence cannot add new items to a list).
2032\obindex{sequence}
2033\obindex{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002034
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002035If the primary is a mapping (dictionary) object, the subscript must
2036have a type compatible with the mapping's key type, and the mapping is
2037then asked to to create a key/datum pair which maps the subscript to
2038the assigned object. This can either replace an existing key/value
2039pair with the same key value, or insert a new key/value pair (if no
2040key with the same value existed).
2041\obindex{mapping}
2042\obindex{dictionary}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002043
2044\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002045If the target is a slicing: The primary expression in the reference is
2046evaluated. It should yield a mutable sequence (list) object. The
2047assigned object should be a sequence object of the same type. Next,
2048the lower and upper bound expressions are evaluated, insofar they are
2049present; defaults are zero and the sequence's length. The bounds
2050should evaluate to (small) integers. If either bound is negative, the
2051sequence's length is added to it. The resulting bounds are clipped to
2052lie between zero and the sequence's length, inclusive. Finally, the
2053sequence object is asked to replace the items indicated by the slice
2054with the items of the assigned sequence. This may change the
2055sequence's length, if it allows it.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002056\indexii{slicing}{assignment}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002057
2058\end{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002059
Guido van Rossumf2612d11991-11-21 13:53:03 +00002060(In the original implementation, the syntax for targets is taken
2061to be the same as for expressions, and invalid syntax is rejected
2062during the code generation phase, causing less detailed error
2063messages.)
2064
Guido van Rossum68c172e1992-01-21 11:34:56 +00002065\section{The {\tt pass} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002066\stindex{pass}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002067
2068\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002069pass_stmt: "pass"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002070\end{verbatim}
2071
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002072\verb\pass\ is a null operation --- when it is executed, nothing
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002073happens. It is useful as a placeholder when a statement is
2074required syntactically, but no code needs to be executed, for example:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002075\indexii{null}{operation}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002076
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002077\begin{verbatim}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002078def f(arg): pass # a function that does nothing (yet)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002079
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002080class C: pass # an class with no methods (yet)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002081\end{verbatim}
2082
Guido van Rossum68c172e1992-01-21 11:34:56 +00002083\section{The {\tt del} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002084\stindex{del}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002085
2086\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002087del_stmt: "del" target_list
Guido van Rossumf2612d11991-11-21 13:53:03 +00002088\end{verbatim}
2089
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002090Deletion is recursively defined very similar to the way assignment is
2091defined. Rather that spelling it out in full details, here are some
2092hints.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002093\indexii{deletion}{target}
2094\indexiii{deletion}{target}{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002095
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002096Deletion of a target list recursively deletes each target, from left
2097to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002098
2099Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002100from the local or global name space, depending on whether the name
2101occurs in a \verb\global\ statement in the same code block.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002102\stindex{global}
2103\indexii{unbinding}{name}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002104
2105Deletion of attribute references, subscriptions and slicings
2106is passed to the primary object involved; deletion of a slicing
2107is in general equivalent to assignment of an empty slice of the
2108right type (but even this is determined by the sliced object).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002109\indexii{attribute}{deletion}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002110
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002111\section{The {\tt print} statement} \label{print}
2112\stindex{print}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002113
2114\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002115print_stmt: "print" [ condition ("," condition)* [","] ]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002116\end{verbatim}
2117
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002118\verb\print\ evaluates each condition in turn and writes the resulting
2119object to standard output (see below). If an object is not a string,
2120it is first converted to a string using the rules for string
2121conversions. The (resulting or original) string is then written. A
2122space is written before each object is (converted and) written, unless
2123the output system believes it is positioned at the beginning of a
2124line. This is the case: (1) when no characters have yet been written
2125to standard output; or (2) when the last character written to standard
2126output is \verb/\n/; or (3) when the last write operation on standard
2127output was not a \verb\print\ statement. (In some cases it may be
2128functional to write an empty string to standard output for this
2129reason.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002130\index{output}
2131\indexii{writing}{values}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002132
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002133A \verb/"\n"/ character is written at the end, unless the \verb\print\
2134statement ends with a comma. This is the only action if the statement
2135contains just the keyword \verb\print\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002136\indexii{trailing}{comma}
2137\indexii{newline}{suppression}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002138
2139Standard output is defined as the file object named \verb\stdout\
2140in the built-in module \verb\sys\. If no such object exists,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002141or if it is not a writable file, a \verb\RuntimeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002142(The original implementation attempts to write to the system's original
2143standard output instead, but this is not safe, and should be fixed.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002144\indexii{standard}{output}
2145\bimodindex{sys}
2146\ttindex{stdout}
2147\exindex{RuntimeError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002148
Guido van Rossum68c172e1992-01-21 11:34:56 +00002149\section{The {\tt return} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002150\stindex{return}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002151
2152\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002153return_stmt: "return" [condition_list]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002154\end{verbatim}
2155
2156\verb\return\ may only occur syntactically nested in a function
2157definition, not within a nested class definition.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002158\indexii{function}{definition}
2159\indexii{class}{definition}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002160
2161If a condition list is present, it is evaluated, else \verb\None\
2162is substituted.
2163
2164\verb\return\ leaves the current function call with the condition
2165list (or \verb\None\) as return value.
2166
2167When \verb\return\ passes control out of a \verb\try\ statement
2168with a \verb\finally\ clause, that finally clause is executed
2169before really leaving the function.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002170\kwindex{finally}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002171
Guido van Rossum68c172e1992-01-21 11:34:56 +00002172\section{The {\tt raise} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002173\stindex{raise}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002174
2175\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002176raise_stmt: "raise" condition ["," condition]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002177\end{verbatim}
2178
2179\verb\raise\ evaluates its first condition, which must yield
2180a string object. If there is a second condition, this is evaluated,
2181else \verb\None\ is substituted.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002182\index{exception}
2183\indexii{raising}{exception}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002184
2185It then raises the exception identified by the first object,
2186with the second one (or \verb\None\) as its parameter.
2187
Guido van Rossum68c172e1992-01-21 11:34:56 +00002188\section{The {\tt break} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002189\stindex{break}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002190
2191\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002192break_stmt: "break"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002193\end{verbatim}
2194
2195\verb\break\ may only occur syntactically nested in a \verb\for\
2196or \verb\while\ loop, not nested in a function or class definition.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002197\stindex{for}
2198\stindex{while}
2199\indexii{loop}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002200
2201It terminates the neares enclosing loop, skipping the optional
2202\verb\else\ clause if the loop has one.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002203\kwindex{else}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002204
2205If a \verb\for\ loop is terminated by \verb\break\, the loop control
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002206target keeps its current value.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002207\indexii{loop control}{target}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002208
2209When \verb\break\ passes control out of a \verb\try\ statement
2210with a \verb\finally\ clause, that finally clause is executed
2211before really leaving the loop.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002212\kwindex{finally}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002213
Guido van Rossum68c172e1992-01-21 11:34:56 +00002214\section{The {\tt continue} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002215\stindex{continue}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002216
2217\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002218continue_stmt: "continue"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002219\end{verbatim}
2220
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002221\verb\continue\ may only occur syntactically nested in a \verb\for\ or
2222\verb\while\ loop, not nested in a function or class definition, and
2223not nested in the \verb\try\ clause of a \verb\try\ statement with a
2224\verb\finally\ clause (it may occur nested in a \verb\except\ or
2225\verb\finally\ clause of a \verb\try\ statement though).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002226\stindex{for}
2227\stindex{while}
2228\indexii{loop}{statement}
2229\kwindex{finally}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002230
2231It continues with the next cycle of the nearest enclosing loop.
2232
Guido van Rossum862c6f11992-01-29 14:47:05 +00002233\section{The {\tt import} statement} \label{import}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002234\stindex{import}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002235
2236\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002237import_stmt: "import" identifier ("," identifier)*
2238 | "from" identifier "import" identifier ("," identifier)*
2239 | "from" identifier "import" "*"
2240\end{verbatim}
2241
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002242Import statements are executed in two steps: (1) find a module, and
2243initialize it if necessary; (2) define a name or names in the local
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002244name space (of the scope where the \verb\import\ statement occurs).
2245The first form (without \verb\from\) repeats these steps for each
2246identifier in the list, the \verb\from\ form performs them once, with
2247the first identifier specifying the module name.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002248\indexii{importing}{module}
2249\indexii{name}{binding}
2250\kwindex{from}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002251
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002252The system maintains a table of modules that have been initialized,
2253indexed by module name. (The current implementation makes this table
2254accessible as \verb\sys.modules\.) When a module name is found in
2255this table, step (1) is finished. If not, a search for a module
2256definition is started. This first looks for a built-in module
2257definition, and if no built-in module if the given name is found, it
2258searches a user-specified list of directories for a file whose name is
2259the module name with extension \verb\".py"\. (The current
2260implementation uses the list of strings \verb\sys.path\ as the search
2261path; it is initialized from the shell environment variable
2262\verb\$PYTHONPATH\, with an installation-dependent default.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002263\ttindex{modules}
2264\ttindex{sys.modules}
2265\indexii{module}{name}
2266\indexii{built-in}{module}
2267\indexii{user-defined}{module}
2268\bimodindex{sys}
2269\ttindex{path}
2270\ttindex{sys.path}
2271\indexii{filename}{extension}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002272
2273If a built-in module is found, its built-in initialization code is
2274executed and step (1) is finished. If no matching file is found,
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002275\verb\ImportError\ is raised. If a file is found, it is parsed,
2276yielding an executable code block. If a syntax error occurs,
2277\verb\SyntaxError\ is raised. Otherwise, an empty module of the given
2278name is created and inserted in the module table, and then the code
2279block is executed in the context of this module. Exceptions during
2280this execution terminate step (1).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002281\indexii{module}{initialization}
2282\exindex{SyntaxError}
2283\exindex{ImportError}
2284\index{code block}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002285
2286When step (1) finishes without raising an exception, step (2) can
2287begin.
2288
2289The first form of \verb\import\ statement binds the module name in the
2290local name space to the module object, and then goes on to import the
2291next identifier, if any. The \verb\from\ from does not bind the
2292module name: it goes through the list of identifiers, looks each one
2293of them up in the module found in step (1), and binds the name in the
2294local name space to the object thus found. If a name is not found,
2295\verb\ImportError\ is raised. If the list of identifiers is replaced
2296by a star (\verb\*\), all names defined in the module are bound,
2297except those beginning with an underscore(\verb\_\).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002298\indexii{name}{binding}
2299\exindex{ImportError}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002300
2301Names bound by import statements may not occur in \verb\global\
2302statements in the same scope.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002303\stindex{global}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002304
2305The \verb\from\ form with \verb\*\ may only occur in a module scope.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002306\kwindex{from}
2307\ttindex{from ... import *}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002308
2309(The current implementation does not enforce the latter two
2310restrictions, but programs should not abuse this freedom, as future
2311implementations may enforce them or silently change the meaning of the
2312program.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002313
Guido van Rossum862c6f11992-01-29 14:47:05 +00002314\section{The {\tt global} statement} \label{global}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002315\stindex{global}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002316
2317\begin{verbatim}
2318global_stmt: "global" identifier ("," identifier)*
Guido van Rossumf2612d11991-11-21 13:53:03 +00002319\end{verbatim}
2320
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002321The \verb\global\ statement is a declaration which holds for the
2322entire current scope. It means that the listed identifiers are to be
2323interpreted as globals. While {\em using} global names is automatic
2324if they are not defined in the local scope, {\em assigning} to global
2325names would be impossible without \verb\global\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002326\indexiii{global}{name}{binding}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002327
2328Names listed in a \verb\global\ statement must not be used in the same
2329scope before that \verb\global\ statement is executed.
2330
2331Name listed in a \verb\global\ statement must not be defined as formal
2332parameters or in a \verb\for\ loop control target, \verb\class\
2333definition, function definition, or \verb\import\ statement.
2334
2335(The current implementation does not enforce the latter two
2336restrictions, but programs should not abuse this freedom, as future
2337implementations may enforce them or silently change the meaning of the
2338program.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00002339
2340\chapter{Compound statements}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002341\indexii{compound}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002342
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002343Compound statements contain (groups of) other statements; they affect
Guido van Rossum60279da1992-04-02 10:24:59 +00002344or control the execution of those other statements in some way. In
2345general, compound statements span multiple lines, although in simple
2346incarnations a whole compound statement may be contained in one line.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002347
2348The \verb\if\, \verb\while\ and \verb\for\ statements implement
2349traditional control flow constructs. \verb\try\ specifies exception
2350handlers and/or cleanup code for a group of statements. Function and
2351class definitions are also syntactically compound statements.
2352
2353Compound statements consist of one or more `clauses'. A clause
2354consists of a header and a `suite'. The clause headers of a
Guido van Rossum60279da1992-04-02 10:24:59 +00002355particular compound statement are all at the same indentation level.
2356Each clause header begins with a uniquely identifying keyword and ends
2357with a colon. A suite is a group of statements controlled by a
2358clause. A suite can be one or more semicolon-separated simple
2359statements on the same line as the header, following the header's
2360colon, or it can be one or more indented statements on subsequent
2361lines. Only the latter form of suite can contain nested compound
2362statements; the following is illegal, mostly because it wouldn't be
2363clear to which \verb\if\ clause a following \verb\else\ clause would
2364belong:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002365\index{clause}
2366\index{suite}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002367
2368\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002369if test1: if test2: print x
Guido van Rossumf2612d11991-11-21 13:53:03 +00002370\end{verbatim}
2371
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002372Also note that the semicolon binds tighter that the colon in this
Guido van Rossum60279da1992-04-02 10:24:59 +00002373context, so that in the following example, either all or none of the
2374\verb\print\ statements are executed:
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002375
2376\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00002377if x < y < z: print x; print y; print z
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002378\end{verbatim}
2379
2380Summarizing:
2381
2382\begin{verbatim}
2383compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
2384suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
2385statement: stmt_list NEWLINE | compound_stmt
2386stmt_list: simple_stmt (";" simple_stmt)* [";"]
2387\end{verbatim}
2388
2389Note that statements always ends in a \verb\NEWLINE\ possibly followed
2390by a \verb\DEDENT\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002391\index{NEWLINE token}
2392\index{DEDENT token}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002393
2394Also note that optional continuation clauses always begin with a
2395keyword that cannot start a statement, thus there are no ambiguities
2396(the `dangling \verb\else\' problem is solved in Python by requiring
2397nested \verb\if\ statements to be indented).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002398\indexii{dangling}{else}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002399
Guido van Rossum60279da1992-04-02 10:24:59 +00002400The formatting of the grammar rules in the following sections places
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002401each clause on a separate line for clarity.
2402
Guido van Rossum68c172e1992-01-21 11:34:56 +00002403\section{The {\tt if} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002404\stindex{if}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002405
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002406The \verb\if\ statement is used for conditional execution:
2407
Guido van Rossumf2612d11991-11-21 13:53:03 +00002408\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002409if_stmt: "if" condition ":" suite
2410 ("elif" condition ":" suite)*
2411 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002412\end{verbatim}
2413
Guido van Rossum60279da1992-04-02 10:24:59 +00002414It selects exactly one of the suites by evaluating the conditions one
2415by one until one is found to be true (see section \ref{Booleans} for
2416the definition of true and false); then that suite is executed (and no
2417other part of the \verb\if\ statement is executed or evaluated). If
2418all conditions are false, the suite of the \verb\else\ clause, if
2419present, is executed.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002420\kwindex{elif}
2421\kwindex{else}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002422
Guido van Rossum68c172e1992-01-21 11:34:56 +00002423\section{The {\tt while} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002424\stindex{while}
2425\indexii{loop}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002426
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002427The \verb\while\ statement is used for repeated execution as long as a
2428condition is true:
2429
Guido van Rossumf2612d11991-11-21 13:53:03 +00002430\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002431while_stmt: "while" condition ":" suite
2432 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002433\end{verbatim}
2434
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002435This repeatedly tests the condition and, if it is true, executes the
2436first suite; if the condition is false (which may be the first time it
Guido van Rossum60279da1992-04-02 10:24:59 +00002437is tested) the suite of the \verb\else\ clause, if present, is
2438executed and the loop terminates.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002439\kwindex{else}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002440
2441A \verb\break\ statement executed in the first suite terminates the
2442loop without executing the \verb\else\ clause's suite. A
2443\verb\continue\ statement executed in the first suited skips the rest
2444of the suite and goes back to testing the condition.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002445\stindex{break}
2446\stindex{continue}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002447
Guido van Rossum68c172e1992-01-21 11:34:56 +00002448\section{The {\tt for} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002449\stindex{for}
2450\indexii{loop}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002451
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002452The \verb\for\ statement is used to iterate over the elements of a
2453sequence (string, tuple or list):
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002454\obindex{sequence}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002455
Guido van Rossumf2612d11991-11-21 13:53:03 +00002456\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002457for_stmt: "for" target_list "in" condition_list ":" suite
2458 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002459\end{verbatim}
2460
Guido van Rossum60279da1992-04-02 10:24:59 +00002461The condition list is evaluated once; it should yield a sequence. The
2462suite is then executed once for each item in the sequence, in the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002463order of ascending indices. Each item in turn is assigned to the
2464target list using the standard rules for assignments, and then the
Guido van Rossum60279da1992-04-02 10:24:59 +00002465suite is executed. When the items are exhausted (which is immediately
2466when the sequence is empty), the suite in the \verb\else\ clause, if
2467present, is executed, and the loop terminates.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002468\kwindex{in}
2469\kwindex{else}
2470\indexii{target}{list}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002471
2472A \verb\break\ statement executed in the first suite terminates the
2473loop without executing the \verb\else\ clause's suite. A
2474\verb\continue\ statement executed in the first suited skips the rest
Guido van Rossum60279da1992-04-02 10:24:59 +00002475of the suite and continues with the next item, or with the \verb\else\
2476clause if there was no next item.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002477\stindex{break}
2478\stindex{continue}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002479
2480The suite may assign to the variable(s) in the target list; this does
2481not affect the next item assigned to it.
2482
Guido van Rossum60279da1992-04-02 10:24:59 +00002483The target list is not deleted when the loop is finished, but if the
2484sequence is empty, it will not have been assigned to at all by the
2485loop.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002486
Guido van Rossum60279da1992-04-02 10:24:59 +00002487Hint: the built-in function \verb\range()\ returns a sequence of
2488integers suitable to emulate the effect of Pascal's \verb\for i := a
2489to b do\; e.g. \verb\range(3)\ returns the list \verb\[0, 1, 2]\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002490\bifuncindex{range}
2491\index{Pascal}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002492
2493{\bf Warning:} There is a subtlety when the sequence is being modified
Guido van Rossum60279da1992-04-02 10:24:59 +00002494by the loop (this can only occur for mutable sequences, i.e. lists).
2495An internal counter is used to keep track of which item is used next,
2496and this is incremented on each iteration. When this counter has
2497reached the length of the sequence the loop terminates. This means that
2498if the suite deletes the current (or a previous) item from the
2499sequence, the next item will be skipped (since it gets the index of
2500the current item which has already been treated). Likewise, if the
2501suite inserts an item in the sequence before the current item, the
2502current item will be treated again the next time through the loop.
2503This can lead to nasty bugs that can be avoided by making a temporary
2504copy using a slice of the whole sequence, e.g.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002505\index{loop!over mutable sequence}
2506\index{mutable sequence!loop over}
Guido van Rossum60279da1992-04-02 10:24:59 +00002507
2508\begin{verbatim}
2509for x in a[:]:
2510 if x < 0: a.remove(x)
2511\end{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002512
Guido van Rossum68c172e1992-01-21 11:34:56 +00002513\section{The {\tt try} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002514\stindex{try}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002515
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002516The \verb\try\ statement specifies exception handlers and/or cleanup
2517code for a group of statements:
2518
Guido van Rossumf2612d11991-11-21 13:53:03 +00002519\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00002520try_stmt: try_exc_stmt | try_fin_stmt
2521try_exc_stmt: "try" ":" suite
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002522 ("except" [condition ["," target]] ":" suite)+
Guido van Rossum60279da1992-04-02 10:24:59 +00002523try_fin_stmt: "try" ":" suite
2524 "finally" ":" suite
Guido van Rossumf2612d11991-11-21 13:53:03 +00002525\end{verbatim}
2526
Guido van Rossum60279da1992-04-02 10:24:59 +00002527There are two forms of \verb\try\ statement: \verb\try...except\ and
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002528\verb\try...finally\. These forms cannot be mixed.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002529
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002530The \verb\try...except\ form specifies one or more exception handlers
2531(the \verb\except\ clauses). When no exception occurs in the
2532\verb\try\ clause, no exception handler is executed. When an
2533exception occurs in the \verb\try\ suite, a search for an exception
2534handler is started. This inspects the except clauses in turn until
2535one is found that matches the exception. A condition-less except
2536clause, if present, must be last; it matches any exception. For an
2537except clause with a condition, that condition is evaluated, and the
2538clause matches the exception if the resulting object is ``compatible''
2539with the exception. An object is compatible with an exception if it
2540is either the object that identifies the exception or it is a tuple
2541containing an item that is compatible with the exception. Note that
2542the object identities must match, i.e. it must be the same object, not
2543just an onject with the same value.
2544\kwindex{except}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002545
2546If no except clause matches the exception, the search for an exception
2547handler continues in the surrounding code and on the invocation stack.
2548
2549If the evaluation of a condition in the header of an except clause
2550raises an exception, the original search for a handler is cancelled
2551and a search starts for the new exception in the surrounding code and
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002552on the call stack (it is treated as if the entire \verb\try\ statement
2553raised the exception).
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002554
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002555When a matching except clause is found, the exception's parameter is
2556assigned to the target specified in that except clause, if present,
2557and the except clause's suite is executed. When the end of this suite
2558is reached, execution continues normally after the entire try
2559statement. (This means that if two nested handlers exist for the same
2560exception, and the exception occurs in the try clause of the inner
2561handler, the outer handler will not handle the exception.)
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002562
2563The \verb\try...finally\ form specifies a `cleanup' handler. The
2564\verb\try\ clause is executed. When no exception occurs, the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002565\verb\finally\ clause is executed. When an exception occurs in the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002566\verb\try\ clause, the exception is temporarily saved, the
2567\verb\finally\ clause is executed, and then the saved exception is
2568re-raised. If the \verb\finally\ clause raises another exception or
2569executes a \verb\return\, \verb\break\ or \verb\continue\ statement,
2570the saved exception is lost.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002571\kwindex{finally}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002572
2573When a \verb\return\ or \verb\break\ statement is executed in the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002574\verb\try\ suite of a \verb\try...finally\ statement, the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002575\verb\finally\ clause is also executed `on the way out'. A
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002576\verb\continue\ statement is illegal in the \verb\try\ clause. (The
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002577reason is a problem with the current implementation --- this
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002578restriction may be lifted in the future).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002579\stindex{return}
2580\stindex{break}
2581\stindex{continue}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002582
Guido van Rossum862c6f11992-01-29 14:47:05 +00002583\section{Function definitions} \label{function}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002584\indexii{function}{definition}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002585
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002586A function definition defines a user-defined function object (see
2587section \ref{types}):
2588\obindex{user-defined function}
2589\obindex{function}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002590
2591\begin{verbatim}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002592funcdef: "def" funcname "(" [parameter_list] ")" ":" suite
2593parameter_list: (parameter ",")* ("*" identifier | parameter [","])
2594sublist: parameter ("," parameter)* [","]
2595parameter: identifier | "(" sublist ")"
2596funcname: identifier
Guido van Rossumf2612d11991-11-21 13:53:03 +00002597\end{verbatim}
2598
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002599A function definition is an executable statement. Its execution binds
2600the function name in the current local name space to a function object
2601(a wrapper around the executable code for the function). This
2602function object contains a reference to the current global name space
2603as the global name space to be used when the function is called.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002604\indexii{function}{name}
2605\indexii{name}{binding}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002606
2607The function definition does not execute the function body; this gets
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002608executed only when the function is called.
2609
2610Function call semantics are described in section \ref{calls}. When a
2611user-defined function is called, the arguments (a.k.a. actual
2612parameters) are bound to the (formal) parameters, as follows:
2613\indexii{function}{call}
2614\indexiii{user-defined}{function}{call}
2615\index{parameter}
2616\index{argument}
2617\indexii{parameter}{formal}
2618\indexii{parameter}{actual}
2619
2620\begin{itemize}
2621
2622\item
2623If there are no formal parameters, there must be no arguments.
2624
2625\item
2626If the formal parameter list does not end in a star followed by an
2627identifier, there must be exactly as many arguments as there are
2628parameters in the formal parameter list (at the top level); the
2629arguments are assigned to the formal parameters one by one. Note that
2630the presence or absence of a trailing comma at the top level in either
2631the formal or the actual parameter list makes no difference. The
2632assignment to a formal parameter is performed as if the parameter
2633occurs on the left hand side of an assignment statement whose right
2634hand side's value is that of the argument.
2635
2636\item
2637If the formal parameter list ends in a star followed by an identifier,
2638preceded by zero or more comma-followed parameters, there must be at
2639least as many arguments as there are parameters preceding the star.
2640Call this number {\em N}. The first {\em N} arguments are assigned to
2641the corresponding formal parameters in the way descibed above. A
2642tuple containing the remaining arguments, if any, is then assigned to
2643the identifier following the star. This variable will always be a
2644tuple: if there are no extra arguments, its value is \verb\()\, if
2645there is just one extra argument, it is a singleton tuple.
2646\indexii{variable length}{parameter list}
2647
2648\end{itemize}
2649
2650Note that the `variable length parameter list' feature only works at
2651the top level of the parameter list; individual parameters use a model
2652corresponding more closely to that of ordinary assignment. While the
2653latter model is generally preferable, because of the greater type
2654safety it offers (wrong-sized tuples aren't silently mistreated),
2655variable length parameter lists are a sufficiently accepted practice
2656in most programming languages that a compromise has been worked out.
2657(And anyway, assignment has no equivalent for empty argument lists.)
Guido van Rossum862c6f11992-01-29 14:47:05 +00002658
2659\section{Class definitions} \label{class}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002660\indexii{class}{definition}
Guido van Rossum862c6f11992-01-29 14:47:05 +00002661
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002662A class definition defines a class object (see section \ref{types}):
2663\obindex{class}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002664
2665\begin{verbatim}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002666classdef: "class" classname [inheritance] ":" suite
2667inheritance: "(" [condition_list] ")"
2668classname: identifier
Guido van Rossumf2612d11991-11-21 13:53:03 +00002669\end{verbatim}
2670
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002671A class definition is an executable statement. It first evaluates the
2672inheritance list, if present. Each item in the inheritance list
2673should evaluate to a class object. The class's suite is then executed
2674in a new execution frame (see section \ref{execframes}), using a newly
2675created local name space and the original global name space.
2676(Usually, the suite contains only function definitions.) When the
2677class's suite finishes execution, its execution frame is discarded but
2678its local name space is saved. A class object is then created using
2679the inheritance list for the base classes and the saved local name
2680space for the attribute dictionary. The class name is bound to this
2681class object in the original local name space.
2682\index{inheritance}
2683\indexii{class}{name}
2684\indexii{name}{binding}
2685\indexii{execution}{frame}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002686
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002687\chapter{Top-level components}
2688
2689The Python interpreter can get its input from a number of sources:
2690from a script passed to it as standard input or as program argument,
2691typed in interactively, from a module source file, etc. This chapter
2692gives the syntax used in these cases.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002693\index{interpreter}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002694
2695\section{Complete Python programs}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002696\index{program}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002697
2698While a language specification need not prescribe how the language
2699interpreter is invoked, it is useful to have a notion of a complete
2700Python program. A complete Python program is executed in a minimally
2701initialized environment: all built-in and standard modules are
2702available, but none have been initialized, except for \verb\sys\
2703(various system services), \verb\builtin\ (built-in functions,
2704exceptions and \verb\None\) and \verb\__main__\. The latter is used
2705to provide the local and global name space for execution of the
2706complete program.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002707\bimodindex{sys}
2708\bimodindex{__main__}
2709\bimodindex{builtin}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002710
2711The syntax for a complete Python program is that for file input,
2712described in the next section.
2713
2714The interpreter may also be invoked in interactive mode; in this case,
2715it does not read and execute a complete program but reads and executes
2716one statement (possibly compound) at a time. The initial environment
2717is identical to that of a complete program; each statement is executed
2718in the name space of \verb\__main__\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002719\index{interactive mode}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002720
2721Under {\UNIX}, a complete program can be passed to the interpreter in
2722three forms: with the {\bf -c} {\it string} command line option, as a
2723file passed as the first command line argument, or as standard input.
2724If the file or standard input is a tty device, the interpreter enters
2725interactive mode; otherwise, it executes the file as a complete
2726program.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002727\index{UNIX}
2728\index{command line}
2729\index{standard input}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002730
2731\section{File input}
2732
2733All input read from non-interactive files has the same form:
2734
2735\begin{verbatim}
2736file_input: (NEWLINE | statement)*
2737\end{verbatim}
2738
2739This syntax is used in the following situations:
2740
2741\begin{itemize}
2742
2743\item when parsing a complete Python program (from a file or from a string);
2744
2745\item when parsing a module;
2746
2747\item when parsing a string passed to \verb\exec()\;
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002748\bifuncindex{exec}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002749
2750\item when parsing a file passed to \verb\execfile()\;
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002751\bifuncindex{execfile}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002752
2753\end{itemize}
2754
2755\section{Interactive input}
2756
2757Input in interactive mode is parsed using the following grammar:
2758
2759\begin{verbatim}
2760interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE
2761\end{verbatim}
2762
2763Note that a (top-level) compound statement must be followed by a blank
2764line in interactive mode; this is needed to help the parser detect the
2765end of the input.
2766
2767\section{Expression input}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002768\index{input}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002769
2770There are two forms of expression input. Both ignore leading
2771whitespace.
2772
2773The string argument to \verb\eval()\ must have the following form:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002774\bifuncindex{eval}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002775
2776\begin{verbatim}
2777eval_input: condition_list NEWLINE*
2778\end{verbatim}
2779
2780The input line read by \verb\input()\ must have the following form:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002781\bifuncindex{input}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002782
2783\begin{verbatim}
2784input_input: condition_list NEWLINE
2785\end{verbatim}
2786
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002787Note: to read `raw' input line without interpretation, you can use the
2788built-in function \verb\raw_input()\ or the \verb\readline()\ method
2789of file objects.
2790\obindex{file}
2791\index{input!raw}
2792\index{raw input}
2793\bifuncindex{raw_index}
2794\ttindex{readline}
2795
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002796\input{ref.ind} % The index
2797
Guido van Rossumf2612d11991-11-21 13:53:03 +00002798\end{document}