blob: 823df62c128b018fb1b86ba979277d32d9750e3f [file] [log] [blame]
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001\documentstyle[11pt,myformat]{report}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002
Guido van Rossum862c6f11992-01-29 14:47:05 +00003\title{\bf Python Reference Manual}
4
Guido van Rossumf2612d11991-11-21 13:53:03 +00005\author{
6 Guido van Rossum \\
7 Dept. CST, CWI, Kruislaan 413 \\
8 1098 SJ Amsterdam, The Netherlands \\
9 E-mail: {\tt guido@cwi.nl}
10}
11
12\begin{document}
13
14\pagenumbering{roman}
15
16\maketitle
17
18\begin{abstract}
19
20\noindent
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000021Python is a simple, yet powerful, interpreted programming language
22that bridges the gap between C and shell programming, and is thus
23ideally suited for ``throw-away programming'' and rapid prototyping.
24Its syntax is put together from constructs borrowed from a variety of
25other languages; most prominent are influences from ABC, C, Modula-3
26and Icon.
Guido van Rossumf2612d11991-11-21 13:53:03 +000027
28The Python interpreter is easily extended with new functions and data
29types implemented in C. Python is also suitable as an extension
30language for highly customizable C applications such as editors or
31window managers.
32
33Python is available for various operating systems, amongst which
34several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S.,
35and MS-DOS.
36
37This reference manual describes the syntax and ``core semantics'' of
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000038the language. It is terse, but attempts to be exact and complete.
39The semantics of non-essential built-in object types and of the
40built-in functions and modules are described in the {\em Python
41Library Reference}. For an informal introduction to the language, see
42the {\em Python Tutorial}.
Guido van Rossumf2612d11991-11-21 13:53:03 +000043
44\end{abstract}
45
46\pagebreak
47
Guido van Rossum670e5a01992-01-17 14:03:20 +000048{
49\parskip = 0mm
Guido van Rossumf2612d11991-11-21 13:53:03 +000050\tableofcontents
Guido van Rossum670e5a01992-01-17 14:03:20 +000051}
Guido van Rossumf2612d11991-11-21 13:53:03 +000052
53\pagebreak
54
55\pagenumbering{arabic}
56
57\chapter{Introduction}
58
59This reference manual describes the Python programming language.
60It is not intended as a tutorial.
61
Guido van Rossum743d1e71992-01-07 16:43:53 +000062While I am trying to be as precise as possible, I chose to use English
63rather than formal specifications for everything except syntax and
64lexical analysis. This should make the document better understandable
65to the average reader, but will leave room for ambiguities.
66Consequently, if you were coming from Mars and tried to re-implement
Guido van Rossum7b632a61992-01-16 17:49:21 +000067Python from this document alone, you might have to guess things and in
68fact you would be implementing quite a different language.
69On the other hand, if you are using
Guido van Rossum743d1e71992-01-07 16:43:53 +000070Python and wonder what the precise rules about a particular area of
Guido van Rossum7b632a61992-01-16 17:49:21 +000071the language are, you should definitely be able to find it here.
Guido van Rossum743d1e71992-01-07 16:43:53 +000072
73It is dangerous to add too many implementation details to a language
74reference document -- the implementation may change, and other
75implementations of the same language may work differently. On the
76other hand, there is currently only one Python implementation, and
Guido van Rossum7b632a61992-01-16 17:49:21 +000077its particular quirks are sometimes worth being mentioned, especially
78where the implementation imposes additional limitations.
Guido van Rossum743d1e71992-01-07 16:43:53 +000079
80Every Python implementation comes with a number of built-in and
81standard modules. These are not documented here, but in the separate
82{\em Python Library Reference} document. A few built-in modules are
83mentioned when they interact in a significant way with the language
84definition.
85
86\section{Notation}
87
88The descriptions of lexical analysis and syntax use a modified BNF
89grammar notation. This uses the following style of definition:
90
91\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000092name: lc_letter (lc_letter | "_")*
93lc_letter: "a"..."z"
Guido van Rossum743d1e71992-01-07 16:43:53 +000094\end{verbatim}
95
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000096The first line says that a \verb\name\ is an \verb\lc_letter\ followed by
97a sequence of zero or more \verb\lc_letter\s and underscores. An
98\verb\lc_letter\ in turn is any of the single characters `a' through `z'.
Guido van Rossum743d1e71992-01-07 16:43:53 +000099(This rule is actually adhered to for the names defined in syntax and
100grammar rules in this document.)
101
102Each rule begins with a name (which is the name defined by the rule)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000103and a colon. A vertical bar
Guido van Rossum7b632a61992-01-16 17:49:21 +0000104(\verb\|\) is used to separate alternatives; it is the least binding
105operator in this notation. A star (\verb\*\) means zero or more
106repetitions of the preceding item; likewise, a plus (\verb\+\) means
107one or more repetitions, and a question mark (\verb\?\) zero or one
108(in other words, the preceding item is optional). These three
109operators bind as tightly as possible; parentheses are used for
Guido van Rossum743d1e71992-01-07 16:43:53 +0000110grouping. Literal strings are enclosed in double quotes. White space
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000111is only meaningful to separate tokens. Rules are normally contained
112on a single line; rules with many alternatives may be formatted
113alternatively with each line after the first beginning with a
114vertical bar.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000115
116In lexical definitions (as the example above), two more conventions
117are used: Two literal characters separated by three dots mean a choice
118of any single character in the given (inclusive) range of ASCII
119characters. A phrase between angular brackets (\verb\<...>\) gives an
120informal description of the symbol defined; e.g., this could be used
121to describe the notion of `control character' if needed.
122
Guido van Rossum7b632a61992-01-16 17:49:21 +0000123Even though the notation used is almost the same, there is a big
Guido van Rossum743d1e71992-01-07 16:43:53 +0000124difference between the meaning of lexical and syntactic definitions:
125a lexical definition operates on the individual characters of the
126input source, while a syntax definition operates on the stream of
127tokens generated by the lexical analysis.
128
Guido van Rossumf2612d11991-11-21 13:53:03 +0000129\chapter{Lexical analysis}
130
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000131A Python program is read by a {\em parser}. Input to the parser is a
132stream of {\em tokens}, generated by the {\em lexical analyzer}. This
133chapter describes how the lexical analyzer breaks a file into tokens.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000134
135\section{Line structure}
136
Guido van Rossum7b632a61992-01-16 17:49:21 +0000137A Python program is divided in a number of logical lines. The end of
138a logical line is represented by the token NEWLINE. Statements cannot
139cross logical line boundaries except where NEWLINE is allowed by the
140syntax (e.g., between statements in compound statements).
Guido van Rossumf2612d11991-11-21 13:53:03 +0000141
142\subsection{Comments}
143
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000144A comment starts with a hash character (\verb\#\) that is not part of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000145a string literal, and ends at the end of the physical line. A comment
146always signifies the end of the logical line. Comments are ignored by
147the syntax.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000148
149\subsection{Line joining}
150
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000151Two or more physical lines may be joined into logical lines using
Guido van Rossum7b632a61992-01-16 17:49:21 +0000152backslash characters (\verb/\/), as follows: when a physical line ends
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000153in a backslash that is not part of a string literal or comment, it is
154joined with the following forming a single logical line, deleting the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000155backslash and the following end-of-line character. For example:
156%
157\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000158moth_names = ['Januari', 'Februari', 'Maart', \
159 'April', 'Mei', 'Juni', \
160 'Juli', 'Augustus', 'September', \
161 'Oktober', 'November', 'December']
Guido van Rossum670e5a01992-01-17 14:03:20 +0000162\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000163
164\subsection{Blank lines}
165
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000166A logical line that contains only spaces, tabs, and possibly a
167comment, is ignored (i.e., no NEWLINE token is generated), except that
168during interactive input of statements, an entirely blank logical line
169terminates a multi-line statement.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000170
171\subsection{Indentation}
172
Guido van Rossum7b632a61992-01-16 17:49:21 +0000173Leading whitespace (spaces and tabs) at the beginning of a logical
174line is used to compute the indentation level of the line, which in
175turn is used to determine the grouping of statements.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000176
Guido van Rossum7b632a61992-01-16 17:49:21 +0000177First, tabs are replaced (from left to right) by one to eight spaces
178such that the total number of characters up to there is a multiple of
179eight (this is intended to be the same rule as used by UNIX). The
180total number of spaces preceding the first non-blank character then
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000181determines the line's indentation. Indentation cannot be split over
182multiple physical lines using backslashes.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000183
184The indentation levels of consecutive lines are used to generate
185INDENT and DEDENT tokens, using a stack, as follows.
186
187Before the first line of the file is read, a single zero is pushed on
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000188the stack; this will never be popped off again. The numbers pushed on
189the stack will always be strictly increasing from bottom to top. At
190the beginning of each logical line, the line's indentation level is
191compared to the top of the stack. If it is equal, nothing happens.
192If it larger, it is pushed on the stack, and one INDENT token is
193generated. If it is smaller, it {\em must} be one of the numbers
194occurring on the stack; all numbers on the stack that are larger are
195popped off, and for each number popped off a DEDENT token is
196generated. At the end of the file, a DEDENT token is generated for
197each number remaining on the stack that is larger than zero.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000198
Guido van Rossum7b632a61992-01-16 17:49:21 +0000199Here is an example of a correctly (though confusingly) indented piece
200of Python code:
201
202\begin{verbatim}
203def perm(l):
Guido van Rossum670e5a01992-01-17 14:03:20 +0000204 # Compute the list of all permutations of l
205
Guido van Rossum7b632a61992-01-16 17:49:21 +0000206 if len(l) <= 1:
207 return [l]
208 r = []
209 for i in range(len(l)):
210 s = l[:i] + l[i+1:]
211 p = perm(s)
212 for x in p:
213 r.append(l[i:i+1] + x)
214 return r
215\end{verbatim}
216
217The following example shows various indentation errors:
218
219\begin{verbatim}
220 def perm(l): # error: first line indented
221 for i in range(len(l)): # error: not indented
222 s = l[:i] + l[i+1:]
223 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
224 for x in p:
225 r.append(l[i:i+1] + x)
226 return r # error: inconsistent indent
227\end{verbatim}
228
229(Actually, the first three errors are detected by the parser; only the
230last error is found by the lexical analyzer -- the indentation of
231\verb\return r\ does not match a level popped off the stack.)
232
Guido van Rossumf2612d11991-11-21 13:53:03 +0000233\section{Other tokens}
234
235Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
236exist: identifiers, keywords, literals, operators, and delimiters.
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000237Spaces and tabs are not tokens, but serve to delimit tokens. Where
238ambiguity exists, a token comprises the longest possible string that
239forms a legal token, when read from left to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000240
Guido van Rossumf2612d11991-11-21 13:53:03 +0000241\section{Identifiers}
242
243Identifiers are described by the following regular expressions:
244
245\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000246identifier: (letter|"_") (letter|digit|"_")*
Guido van Rossumf2612d11991-11-21 13:53:03 +0000247letter: lowercase | uppercase
Guido van Rossum743d1e71992-01-07 16:43:53 +0000248lowercase: "a"..."z"
249uppercase: "A"..."Z"
250digit: "0"..."9"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000251\end{verbatim}
252
Guido van Rossum670e5a01992-01-17 14:03:20 +0000253Identifiers are unlimited in length. Case is significant.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000254
Guido van Rossum670e5a01992-01-17 14:03:20 +0000255\subsection{Keywords}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000256
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000257The following identifiers are used as reserved words, or {\em
Guido van Rossum7b632a61992-01-16 17:49:21 +0000258keywords} of the language, and cannot be used as ordinary
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000259identifiers. They must be spelled exactly as written here:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000260
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000261\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000262and del for in print
263break elif from is raise
264class else global not return
265continue except if or try
266def finally import pass while
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000267\end{verbatim}
268
Guido van Rossum743d1e71992-01-07 16:43:53 +0000269% # This Python program sorts and formats the above table
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000270% import string
271% l = []
272% try:
273% while 1:
274% l = l + string.split(raw_input())
275% except EOFError:
276% pass
277% l.sort()
278% for i in range((len(l)+4)/5):
279% for j in range(i, len(l), 5):
280% print string.ljust(l[j], 10),
281% print
Guido van Rossumf2612d11991-11-21 13:53:03 +0000282
283\section{Literals}
284
285\subsection{String literals}
286
287String literals are described by the following regular expressions:
288
289\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000290stringliteral: "'" stringitem* "'"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000291stringitem: stringchar | escapeseq
Guido van Rossum743d1e71992-01-07 16:43:53 +0000292stringchar: <any ASCII character except newline or "\" or "'">
293escapeseq: "'" <any ASCII character except newline>
Guido van Rossumf2612d11991-11-21 13:53:03 +0000294\end{verbatim}
295
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000296String literals cannot span physical line boundaries. Escape
297sequences in strings are actually interpreted according to rules
298simular to those used by Standard C. The recognized escape sequences
299are:
300
301\begin{center}
302\begin{tabular}{|l|l|}
303\hline
304\verb/\\/ & Backslash (\verb/\/) \\
305\verb/\'/ & Single quote (\verb/'/) \\
306\verb/\a/ & ASCII Bell (BEL) \\
307\verb/\b/ & ASCII Backspace (BS) \\
Guido van Rossum7b632a61992-01-16 17:49:21 +0000308%\verb/\E/ & ASCII Escape (ESC) \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000309\verb/\f/ & ASCII Formfeed (FF) \\
310\verb/\n/ & ASCII Linefeed (LF) \\
311\verb/\r/ & ASCII Carriage Return (CR) \\
312\verb/\t/ & ASCII Horizontal Tab (TAB) \\
313\verb/\v/ & ASCII Vertical Tab (VT) \\
314\verb/\/{\em ooo} & ASCII character with octal value {\em ooo} \\
Guido van Rossum743d1e71992-01-07 16:43:53 +0000315\verb/\x/{em xx...} & ASCII character with hex value {\em xx...} \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000316\hline
317\end{tabular}
318\end{center}
319
Guido van Rossum7b632a61992-01-16 17:49:21 +0000320In strict compatibility with in Standard C, up to three octal digits are
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000321accepted, but an unlimited number of hex digits is taken to be part of
322the hex escape (and then the lower 8 bits of the resulting hex number
Guido van Rossum7b632a61992-01-16 17:49:21 +0000323are used in all current implementations...).
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000324
Guido van Rossum7b632a61992-01-16 17:49:21 +0000325All unrecognized escape sequences are left in the string unchanged,
326i.e., {\em the backslash is left in the string.} (This rule is
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000327useful when debugging: if an escape sequence is mistyped, the
Guido van Rossum743d1e71992-01-07 16:43:53 +0000328resulting output is more easily recognized as broken. It also helps a
329great deal for string literals used as regular expressions or
330otherwise passed to other modules that do their own escape handling --
331but you may end up quadrupling backslashes that must appear literally.)
Guido van Rossumf2612d11991-11-21 13:53:03 +0000332
333\subsection{Numeric literals}
334
Guido van Rossum670e5a01992-01-17 14:03:20 +0000335There are three types of numeric literals: plain integers, long
336integers, and floating point numbers.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000337
338Integers and long integers are described by the following regular expressions:
339
340\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000341longinteger: integer ("l"|"L")
Guido van Rossumf2612d11991-11-21 13:53:03 +0000342integer: decimalinteger | octinteger | hexinteger
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000343decimalinteger: nonzerodigit digit* | "0"
344octinteger: "0" octdigit+
345hexinteger: "0" ("x"|"X") hexdigit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000346
Guido van Rossum743d1e71992-01-07 16:43:53 +0000347nonzerodigit: "1"..."9"
348octdigit: "0"..."7"
349hexdigit: digit|"a"..."f"|"A"..."F"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000350\end{verbatim}
351
Guido van Rossum670e5a01992-01-17 14:03:20 +0000352Although both lower case `l'and upper case `L' are allowed as suffix
353for long integers, it is strongly recommended to always use `L', since
354the letter `l' looks too much like the digit `1'.
355
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000356Plain integer decimal literals must be at most $2^{31} - 1$ (i.e., the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000357largest positive integer, assuming 32-bit arithmetic); octal and
358hexadecimal literals may be as large as $2^{32} - 1$. There is no limit
359for long integer literals.
360
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000361Some examples of plain and long integer literals:
Guido van Rossum670e5a01992-01-17 14:03:20 +0000362
363\begin{verbatim}
3647 2147483647 0177 0x80000000
3653L 79228162514264337593543950336L 0377L 0100000000L
366\end{verbatim}
367
Guido van Rossumf2612d11991-11-21 13:53:03 +0000368Floating point numbers are described by the following regular expressions:
369
370\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000371floatnumber: pointfloat | exponentfloat
372pointfloat: [intpart] fraction | intpart "."
373exponentfloat: (intpart | pointfloat) exponent
Guido van Rossumf2612d11991-11-21 13:53:03 +0000374intpart: digit+
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000375fraction: "." digit+
376exponent: ("e"|"E") ["+"|"-"] digit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000377\end{verbatim}
378
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000379The allowed range of floating point literals is
380implementation-dependent.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000381
382Some examples of floating point literals:
Guido van Rossum7b632a61992-01-16 17:49:21 +0000383
384\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00003853.14 10. .001 1e100 3.14e-10
Guido van Rossum7b632a61992-01-16 17:49:21 +0000386\end{verbatim}
387
Guido van Rossum670e5a01992-01-17 14:03:20 +0000388Note that numeric literals do not include a sign; a phrase like
389\verb\-1\ is actually an expression composed of the operator
Guido van Rossum7b632a61992-01-16 17:49:21 +0000390\verb\-\ and the literal \verb\1\.
391
Guido van Rossumf2612d11991-11-21 13:53:03 +0000392\section{Operators}
393
394The following tokens are operators:
395
396\begin{verbatim}
397+ - * / %
398<< >> & | ^ ~
Guido van Rossum743d1e71992-01-07 16:43:53 +0000399< == > <= <> != >=
Guido van Rossumf2612d11991-11-21 13:53:03 +0000400\end{verbatim}
401
Guido van Rossum743d1e71992-01-07 16:43:53 +0000402The comparison operators \verb\<>\ and \verb\!=\ are alternate
403spellings of the same operator.
404
Guido van Rossumf2612d11991-11-21 13:53:03 +0000405\section{Delimiters}
406
Guido van Rossum743d1e71992-01-07 16:43:53 +0000407The following tokens serve as delimiters or otherwise have a special
408meaning:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000409
410\begin{verbatim}
411( ) [ ] { }
Guido van Rossum743d1e71992-01-07 16:43:53 +0000412; , : . ` =
Guido van Rossumf2612d11991-11-21 13:53:03 +0000413\end{verbatim}
414
Guido van Rossum7b632a61992-01-16 17:49:21 +0000415The following printing ASCII characters are not used in Python (except
416in string literals and in comments). Their occurrence is an
417unconditional error:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000418
419\begin{verbatim}
420! @ $ " ?
421\end{verbatim}
422
Guido van Rossum7b632a61992-01-16 17:49:21 +0000423They may be used by future versions of the language though!
424
Guido van Rossumf2612d11991-11-21 13:53:03 +0000425\chapter{Execution model}
426
Guido van Rossum743d1e71992-01-07 16:43:53 +0000427\section{Objects, values and types}
428
429I won't try to define rigorously here what an object is, but I'll give
430some properties of objects that are important to know about.
431
432Every object has an identity, a type and a value. An object's {\em
433identity} never changes once it has been created; think of it as the
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000434object's address in memory. An object's {\em type} determines the
435operations that an object supports (e.g., ``does it have a length?'')
436and also defines the ``meaning'' of the object's value. The type also
Guido van Rossum670e5a01992-01-17 14:03:20 +0000437never changes. The {\em value} of some objects can change; whether
438this is possible is a property of its type.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000439
440Objects are never explicitly destroyed; however, when they become
Guido van Rossum670e5a01992-01-17 14:03:20 +0000441unreachable they may be garbage-collected. An implementation is
442allowed to delay garbage collection or omit it altogether -- it is a
443matter of implementation quality how garbage collection is
444implemented, as long as no objects are collected that are still
445reachable. (Implementation note: the current implementation uses a
Guido van Rossum743d1e71992-01-07 16:43:53 +0000446reference-counting scheme which collects most objects as soon as they
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000447become unreachable, but never collects garbage containing circular
Guido van Rossum743d1e71992-01-07 16:43:53 +0000448references.)
449
Guido van Rossum670e5a01992-01-17 14:03:20 +0000450Note that the use of the implementation's tracing or debugging
451facilities may keep objects alive that would normally be collectable.
452
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000453Some objects contain references to ``external'' resources such as open
454files or windows. It is understood that these resources are freed
455when the object is garbage-collected, but since garbage collection is
456not guaranteed to happen, such objects also provide an explicit way to
457release the external resource, usually a \verb\close\ method.
458Programs are strongly recommended to always explicitly close such
459objects.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000460
461Some objects contain references to other objects. These references
462are part of the object's value; in most cases, when such a
463``container'' object is compared to another (of the same type), the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000464comparison applies to the {\em values} of the referenced objects (not
465their identities).
Guido van Rossum743d1e71992-01-07 16:43:53 +0000466
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000467Types affect almost all aspects of an object's life. Even the meaning
468of object identity is affected in some sense: for immutable types,
469operations that compute new values may actually return a reference to
470any existing object with the same type and value, while for mutable
471objects this is not allowed. E.g., after
Guido van Rossum743d1e71992-01-07 16:43:53 +0000472
473\begin{verbatim}
474a = 1; b = 1; c = []; d = []
475\end{verbatim}
476
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000477\verb\a\ and \verb\b\ may or may not refer to the same object with the
478value one, depending on the implementation, but \verb\c\ and \verb\d\
479are guaranteed to refer to two different, unique, newly created empty
480lists.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000481
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000482\section{Code blocks, execution frames, and name spaces}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000483
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000484A ``code block'' is a piece of Python program text that can be
485executed as a unit, such as a module, a class definition or a function
486body. Some code blocks (like modules) are executed only once, others
487(like function bodies) may be executed many times. Code block may
488textually contain other code blocks. Code blocks may invoke other
489code blocks (that aren't textually contained) as part of their
490execution.
491
492Each command typed interactively is a separate code block; a script
493file is a code block; the string argument passed to the built-in
494functions \verb\eval\ and \verb\exec\ are code blocks; the expression
495read and evaluated by the built-in function \verb\input\ is a code
496block.
497
498A code block is executed in an ``execution frame''. An execution
499frame contains some administrative information (used for debugging),
500determines where and how execution continues after the code block's
501execution has completed, and (perhaps most importantly) defines two
502``name spaces'' that affect execution of the code block.
503
504A name space is a mapping from names (identifiers) to objects. A
505particular name space may be referenced by more than one execution
506frame, and from other places as well. Adding a name to a name space
507is called ``binding'' a name (to an object); changing the mapping of a
508name is called ``rebinding''; removing a name from the name space is
509called ``unbinding''. Name spaces are functionally equivalent to
510dictionaries (described below).
511
512The ``local name space'' of an execution frame determines the default
513place where names are defined and searched. The ``global name
514space'' determines the place where names listed in \verb\global\
515statements are defined and searched, and where names that are not
516explicitly bound in the current code block are searched.
517
518Whether a name is local or global in a code block is determined by
519static inspection of the source text for the code block: in the
520absence of \verb\global\ statements, a name that is bound anywhere in
521the code block is local in the entire code block; all other names are
522considered global. The \verb\global\ statement forces global
523interpretation of selected names throughout the code block. The
524following constructs bind names: formal parameters, \verb\import\
525statements, class and function definitions (these bind the class or
526function name), and targets that are identifiers if occurring in an
527assignment, \verb\for\ loop header, or \verb\except\ clause header.
528(A target occurring in a \verb\del\ statement does not bind a name.)
529
530When a global name is not found in the global name space, it is
531searched in the list of ``built-in'' names (this is actually the
532global name space of the module \verb\builtin\). When a name is not
533found at all, the \verb\NameError\ exception is raised.
534
535The following table lists the meaning of the local and global name
536space for various types of code blocks. The name space for a
537particular module is automatically created when the module is first
538referenced.
539
540\begin{center}
541\begin{tabular}{|l|l|l|l|}
542\hline
543Code block type & Global name space & Local name space & Notes \\
544\hline
545Module & n.s. for this module & same as global & \\
546Script & n.s. for \verb\__main__\ & same as global & \\
547Interactive command & n.s. for \verb\__main__\ & same as global & \\
548Class definition & global n.s. of containing block & new n.s. & \\
549Function body & global n.s. of containing block & new n.s. & \\
550String passed to \verb\exec\ or \verb\eval\
551 & global n.s. of caller & local n.s. of caller & (1) \\
552File read by \verb\execfile\
553 & global n.s. of caller & local n.s. of caller & (1) \\
554Expression read by \verb\input\
555 & global n.s. of caller & local n.s. of caller & \\
556\hline
557\end{tabular}
558\end{center}
559
560Notes:
561\begin{description}
562\item[(1)] The global and local name space for these functions can be
563overridden with optional extra arguments.
564\end{description}
565
566\section{Exceptions}
567
568Exceptions are a means of breaking out of the normal flow of control
569of a code block in order to handle errors (or other exceptional
570conditions). An exception is ``raised'' at the point where the error
571is detected; it may be ``handled'' by the surrounding code block or by any
572code block that directly or indirectly invoked the code block where
573the error occurred.
574
575The Python interpreter raises an exception when it detects an run-time
576error (such as division by zero). A Python program can also
577explicitly raise an exception with the \verb\raise\ statement.
578Exception handlers are specified with the \verb\try...except\ statement.
579
580Python uses the ``termination'' model of error handling: a handler can
581find out what happened and continue execution at an outer level, but
582it cannot repair the cause of the error and retry the failing
583operation (except by re-entering the the offending piece of code from
584the top).
585
586When an exception is not handled at all, the interpreter terminates
587execution of the program, or returns to its interactive main loop.
588
589Exceptions are identified by string objects. Two different string
590objects with the same value identify different exceptions.
591
592When an exception is raised, an object (maybe \verb\None\) is passed
593as the exception's ``parameter''; this object does not affect the
594selection of an exception handler, but is passed to the selected
595exception handler as additional information.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000596
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000597\chapter{The standard type hierarchy}
598
Guido van Rossum862c6f11992-01-29 14:47:05 +0000599Below is a list of the types that are built into Python. Extension
600modules written in C can define additional types. Future versions of
601Python may add types to the type hierarchy (e.g., rational or complex
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000602numbers, lists of efficiently stored integers, etc.).
603
Guido van Rossum862c6f11992-01-29 14:47:05 +0000604Some type descriptions contain a paragraph listing `special
605attributes'. These are attributes that provide access to the
606implementation and are not intended for general use. Their definition
607may change in the future. There are also some `generic' special
608attributes, not listed with the individual objects: \verb\__methods__\
609is a list of the method names of a built-in object, if it has any;
610\verb\__members__\ is a list of the data attribute names of a built-in
611object, if it has any.
612
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000613\begin{description}
614
615\item[None]
616This type has a single value. There is a single object with this value.
617This object is accessed through the built-in name \verb\None\.
618It is returned from functions that don't explicitly return an object.
619
620\item[Numbers]
621These are created by numeric literals and returned as results
622by arithmetic operators and arithmetic built-in functions.
623Numeric objects are immutable; once created their value never changes.
624Python numbers are of course strongly related to mathematical numbers,
625but subject to the limitations of numerical representation in computers.
626
627Python distinguishes between integers and floating point numbers:
628
629\begin{description}
630\item[Integers]
631These represent elements from the mathematical set of whole numbers.
632
633There are two types of integers:
634
635\begin{description}
636
637\item[Plain integers]
638These represent numbers in the range $-2^{31}$ through $2^{31}-1$.
639(The range may be larger on machines with a larger natural word
640size, but not smaller.)
641When the result of an operation falls outside this range, the
642exception \verb\OverflowError\ is raised.
643For the purpose of shift and mask operations, integers are assumed to
644have a binary, 2's complement notation using 32 or more bits, and
645hiding no bits from the user (i.e., all $2^{32}$ different bit
646patterns correspond to different values).
647
648\item[Long integers]
649These represent numbers in an unlimited range, subject to avaiable
650(virtual) memory only. For the purpose of shift and mask operations,
651a binary representation is assumed, and negative numbers are
652represented in a variant of 2's complement which gives the illusion of
653an infinite string of sign bits extending to the left.
654
655\end{description} % Integers
656
657The rules for integer representation are intended to give the most
658meaningful interpretation of shift and mask operations involving
659negative integers and the least surprises when switching between the
660plain and long integer domains. For any operation except left shift,
661if it yields a result in the plain integer domain without causing
662overflow, it will yield the same result in the long integer domain or
663when using mixed operands.
664
665\item[Floating point numbers]
666These represent machine-level double precision floating point numbers.
667You are at the mercy of the underlying machine architecture and
668C implementation for the accepted range and handling of overflow.
669
670\end{description} % Numbers
671
672\item[Sequences]
673These represent finite ordered sets indexed by natural numbers.
674The built-in function \verb\len()\ returns the number of elements
675of a sequence. When this number is $n$, the index set contains
676the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence
677\verb\a\ is selected by \verb\a[i]\.
678
679Sequences also support slicing: \verb\a[i:j]\ selects all elements
680with index $k$ such that $i < k < j$. When used as an expression,
681a slice is a sequence of the same type -- this implies that the
682index set is renumbered so that it starts at 0 again.
683
684Sequences are distinguished according to their mutability:
685
686\begin{description}
687%
688\item[Immutable sequences]
689An object of an immutable sequence type cannot change once it is
690created. (If the object contains references to other objects,
691these other objects may be mutable and may be changed; however
692the collection of objects directly referenced by an immutable object
693cannot change.)
694
695The following types are immutable sequences:
696
697\begin{description}
698
699\item[Strings]
700The elements of a string are characters. There is no separate
701character type; a character is represented by a string of one element.
702Characters represent (at least) 8-bit bytes. The built-in
703functions \verb\chr()\ and \verb\ord()\ convert between characters
704and nonnegative integers representing the byte values.
705Bytes with the values 0-127 represent the corresponding ASCII values.
706
707(On systems whose native character set is not ASCII, strings may use
708EBCDIC in their internal representation, provided the functions
709\verb\chr()\ and \verb\ord()\ implement a mapping between ASCII and
710EBCDIC, and string comparisons preserve the ASCII order.
711Or perhaps someone can propose a better rule?)
712
713\item[Tuples]
714The elements of a tuple are arbitrary Python objects.
715Tuples of two or more elements are formed by comma-separated lists
716of expressions. A tuple of one element can be formed by affixing
717a comma to an expression (an expression by itself of course does
718not create a tuple). An empty tuple can be formed by enclosing
719`nothing' in parentheses.
720
721\end{description} % Immutable sequences
722
723\item[Mutable sequences]
724Mutable sequences can be changed after they are created.
725The subscript and slice notations can be used as the target
726of assignment and \verb\del\ (delete) statements.
727
728There is currently a single mutable sequence type:
729
730\begin{description}
731
732\item[Lists]
733The elements of a list are arbitrary Python objects.
734Lists are formed by placing a comma-separated list of expressions
735in square brackets. (Note that there are no special cases for lists
736of length 0 or 1.)
737
738\end{description} % Mutable sequences
739
740\end{description} % Sequences
741
742\item[Mapping types]
743These represent finite sets of objects indexed by arbitrary index sets.
744The subscript notation \verb\a[k]\ selects the element indexed
745by \verb\k\ from the mapping \verb\a\; this can be used in
746expressions and as the target of assignments or \verb\del\ statements.
747The built-in function \verb\len()\ returns the number of elements
748in a mapping.
749
750There is currently a single mapping type:
751
752\begin{description}
753
754\item[Dictionaries]
755These represent finite sets of objects indexed by strings.
756Dictionaries are created by the \verb\{...}\ notation (see section
757\ref{dict}). (Implementation note: the strings used for indexing must
758not contain null bytes.)
759
760\end{description} % Mapping types
761
762\item[Callable types]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000763These are the types to which the function call operation (written as
764\verb\function(argument, argument, ...)\) can be applied:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000765
766\begin{description}
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000767
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000768\item[User-defined functions]
Guido van Rossum862c6f11992-01-29 14:47:05 +0000769A user-defined function is created by a function definition (see
770section \ref{function}). It should be called with an argument list
771containing the same number of items as the function's formal parameter
772list.
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000773
774Special read-only attributes: \verb\func_code\ is the code object
775representing the compiled function body, and \verb\func_globals\ is (a
776reference to) the dictionary that holds the function's global
777variables -- it implements the global name space of the module in
778which the function was defined.
779
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000780\item[User-defined methods]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000781A user-defined method (a.k.a. {\tt object closure}) is a pair of a
782class instance object and a user-defined function. It should be
783called with an argument list containing one item less than the number
784of items in the function's formal parameter list. When called, the
785class instance becomes the first argument, and the call arguments are
786shifted one to the right.
787
788Special read-only attributes: \verb\im_self\ is the class instance
789object, \verb\im_func\ is the function object.
790
791\item[Built-in functions]
792A built-in function object is a wrapper around a C function. Examples
793of built-in functions are \verb\len\ and \verb\math.sin\. There
794are no special attributes. The number and type of the arguments are
795determined by the C function.
796
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000797\item[Built-in methods]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000798This is really a different disguise of a built-in function, this time
799containing an object passed to the C function as an implicit extra
800argument. An example of a built-in method is \verb\list.append\ if
801\verb\list\ is a list object.
802
803\item[Classes]
804Class objects are described below. When a class object is called as a
805parameterless function, a new class instance (also described below) is
806created and returned. The class's initialization function is not
807called -- this is the responsibility of the caller. It is illegal to
808call a class object with one or more arguments.
809
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000810\end{description}
811
812\item[Modules]
Guido van Rossum862c6f11992-01-29 14:47:05 +0000813Modules are imported by the \verb\import\ statement (see section
814\ref{import}). A module object is a container for a module's name
815space, which is a dictionary (the same dictionary as referenced by the
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000816\verb\func_globals\ attribute of functions defined in the module).
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000817Module attribute references are translated to lookups in this
818dictionary. A module object does not contain the code object used to
819initialize the module (since it isn't needed once the initialization
820is done).
821
Guido van Rossum862c6f11992-01-29 14:47:05 +0000822Attribute assignment update the module's name space dictionary.
823
824Special read-only attributes: \verb\__dict__\ yields the module's name
825space as a dictionary object; \verb\__name__\ yields the module's name.
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000826
827\item[Classes]
Guido van Rossum862c6f11992-01-29 14:47:05 +0000828Class objects are created by class definitions (see section
829\ref{class}). A class is a container for a dictionary containing the
830class's name space. Class attribute references are translated to
831lookups in this dictionary. When an attribute name is not found
832there, the attribute search continues in the base classes. The search
833is depth-first, left-to-right in the order of their occurrence in the
834base class list.
835
836Attribute assignments update the class's dictionary, never the
837dictionary of a base class.
838
839A class can be called as a parameterless function to yield a class
840instance (see above).
841
842Special read-only attributes: \verb\__dict__\ yields te dictionary
843containing the class's name space; \verb\__bases__\ yields a tuple
844(possibly empty or a singleton) containing the base classes, in the
845order of their occurrence in the base class list.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000846
847\item[Class instances]
Guido van Rossum862c6f11992-01-29 14:47:05 +0000848A class instance is created by calling a class object as a
849parameterless function. A class instance has a dictionary in which
850attribute references are searched. When an attribute is not found
851there, and the instance's class has an attribute by that name, and
852that class attribute is a user-defined function (and in no other
853cases), the instance attribute reference yields a user-defined method
854object (see above) constructed from the instance and the function.
855
856Attribute assignments update the instance's dictionary.
857
858Special read-only attributes: \verb\__dict__\ yields the attribute
859dictionary; \verb\__class__\ yields the instance's class.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000860
861\item[Files]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000862A file object represents an open file. (It is a wrapper around a C
863{\tt stdio} file pointer.) File objects are created by the
864\verb\open()\ built-in function, and also by \verb\posix.popen()\ and
865the \verb\makefile\ method of socket objects. \verb\sys.stdin\,
866\verb\sys.stdout\ and \verb\sys.stderr\ are file objects corresponding
867the the interpreter's standard input, output and error streams.
868See the Python Library Reference for methods of file objects and other
869details.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000870
871\item[Internal types]
872A few types used internally by the interpreter are exposed to the user.
873Their definition may change with future versions of the interpreter,
874but they are mentioned here for completeness.
875
876\begin{description}
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000877
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000878\item[Code objects]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000879Code objects represent executable code. The difference between a code
880object and a function object is that the function object contains an
881explicit reference to the function's context (the module in which it
882was defined) which a code object contains no context. There is no way
883to execute a bare code object.
884
885Special read-only attributes: \verb\co_code\ is a string representing
886the sequence of instructions; \verb\co_consts\ is a list of literals
887used by the code; \verb\co_names\ is a list of names (strings) used by
888the code; \verb\co_filename\ is the filename from which the code was
889compiled. (To find out the line numbers, you would have to decode the
890instructions; the standard library module \verb\dis\ contains an
891example of how to do this.)
892
893\item[Frame objects]
894Frame objects represent execution frames. They may occur in traceback
895objects (see below).
896
897Special read-only attributes: \verb\f_back\ is to the previous
898stack frame (towards the caller), or \verb\None\ if this is the bottom
899stack frame; \verb\f_code\ is the code object being executed in this
900frame; \verb\f_globals\ is the dictionary used to look up global
901variables; \verb\f_locals\ is used for local variables;
902\verb\f_lineno\ gives the line number and \verb\f_lasti\ gives the
903precise instruction (this is an index into the instruction string of
904the code object).
905
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000906\item[Traceback objects]
Guido van Rossum255ad6e1992-01-28 18:10:46 +0000907Traceback objects represent a stack trace of an exception. A
908traceback object is created when an exception occurs. When the search
909for an exception handler unwinds the execution stack, at each unwound
910level a traceback object is inserted in front of the current
911traceback. When an exception handler is entered, the stack trace is
912made available to the program as \verb\sys.exc_traceback\. When the
913program contains no suitable handler, the stack trace is written
914(nicely formatted) to the standard error stream; if the interpreter is
915interactive, it is made available to the user as
916\verb\sys.last_traceback\.
917
918Special read-only attributes: \verb\tb_next\ is the next level in the
919stack trace (towards the frame where the exception occurred), or
920\verb\None\ if there is no next level; \verb\tb_frame\ points to the
921execution frame of the current level; \verb\tb_lineno\ gives the line
922number where the exception occurred; \verb\tb_lasti\ indicates the
923precise instruction. The line number and last instruction in the
924traceback may differ from the line number of its frame object if the
925exception occurred in a \verb\try\ statement with no matching
926\verb\except\ clause or with a \verb\finally\ clause.
927
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000928\end{description} % Internal types
929
930\end{description} % Types
931
Guido van Rossumf2612d11991-11-21 13:53:03 +0000932\chapter{Expressions and conditions}
933
Guido van Rossum743d1e71992-01-07 16:43:53 +0000934From now on, extended BNF notation will be used to describe syntax,
935not lexical analysis.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000936
937This chapter explains the meaning of the elements of expressions and
938conditions. Conditions are a superset of expressions, and a condition
Guido van Rossum670e5a01992-01-17 14:03:20 +0000939may be used wherever an expression is required by enclosing it in
940parentheses. The only places where expressions are used in the syntax
941instead of conditions is in expression statements and on the
942right-hand side of assignments; this catches some nasty bugs like
943accedentally writing \verb\x == 1\ instead of \verb\x = 1\.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000944
Guido van Rossum670e5a01992-01-17 14:03:20 +0000945The comma has several roles in Python's syntax. It is usually an
Guido van Rossum743d1e71992-01-07 16:43:53 +0000946operator with a lower precedence than all others, but occasionally
Guido van Rossum670e5a01992-01-17 14:03:20 +0000947serves other purposes as well; e.g., it separates function arguments,
948is used in list and dictionary constructors, and has special semantics
949in \verb\print\ statements.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000950
951When (one alternative of) a syntax rule has the form
952
953\begin{verbatim}
954name: othername
955\end{verbatim}
956
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000957and no semantics are given, the semantics of this form of \verb\name\
958are the same as for \verb\othername\.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000959
960\section{Arithmetic conversions}
961
962When a description of an arithmetic operator below uses the phrase
963``the numeric arguments are converted to a common type'',
964this both means that if either argument is not a number, a
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000965\verb\TypeError\ exception is raised, and that otherwise
Guido van Rossumf2612d11991-11-21 13:53:03 +0000966the following conversions are applied:
967
968\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000969\item first, if either argument is a floating point number,
Guido van Rossumf2612d11991-11-21 13:53:03 +0000970 the other is converted to floating point;
971\item else, if either argument is a long integer,
972 the other is converted to long integer;
Guido van Rossum670e5a01992-01-17 14:03:20 +0000973\item otherwise, both must be plain integers and no conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +0000974 is necessary.
975\end{itemize}
976
Guido van Rossumf2612d11991-11-21 13:53:03 +0000977\section{Atoms}
978
Guido van Rossum670e5a01992-01-17 14:03:20 +0000979Atoms are the most basic elements of expressions. Forms enclosed in
980reverse quotes or in parentheses, brackets or braces are also
981categorized syntactically as atoms. The syntax for atoms is:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000982
983\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000984atom: identifier | literal | enclosure
985enclosure: parenth_form | list_display | dict_display | string_conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +0000986\end{verbatim}
987
988\subsection{Identifiers (Names)}
989
990An identifier occurring as an atom is a reference to a local, global
Guido van Rossum670e5a01992-01-17 14:03:20 +0000991or built-in name binding. If a name can be assigned to anywhere in a
992code block, and is not mentioned in a \verb\global\ statement in that
993code block, it refers to a local name throughout that code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000994Otherwise, it refers to a global name if one exists, else to a
995built-in name.
996
Guido van Rossum670e5a01992-01-17 14:03:20 +0000997When the name is bound to an object, evaluation of the atom yields
998that object. When a name is not bound, an attempt to evaluate it
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000999raises a \verb\NameError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001000
1001\subsection{Literals}
1002
Guido van Rossum670e5a01992-01-17 14:03:20 +00001003Python knows string and numeric literals:
1004
1005\begin{verbatim}
1006literal: stringliteral | integer | longinteger | floatnumber
1007\end{verbatim}
1008
Guido van Rossumf2612d11991-11-21 13:53:03 +00001009Evaluation of a literal yields an object of the given type
1010(string, integer, long integer, floating point number)
1011with the given value.
1012The value may be approximated in the case of floating point literals.
1013
Guido van Rossum670e5a01992-01-17 14:03:20 +00001014All literals correspond to immutable data types, and hence the
1015object's identity is less important than its value. Multiple
1016evaluations of literals with the same value (either the same
1017occurrence in the program text or a different occurrence) may obtain
1018the same object or a different object with the same value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001019
1020(In the original implementation, all literals in the same code block
1021with the same type and value yield the same object.)
1022
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001023\subsection{Parenthesized forms}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001024
Guido van Rossum670e5a01992-01-17 14:03:20 +00001025A parenthesized form is an optional condition list enclosed in
1026parentheses:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001027
Guido van Rossum670e5a01992-01-17 14:03:20 +00001028\begin{verbatim}
1029parenth_form: "(" [condition_list] ")"
1030\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001031
Guido van Rossum670e5a01992-01-17 14:03:20 +00001032A parenthesized condition list yields whatever that condition list
1033yields.
1034
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001035An empty pair of parentheses yields an empty tuple object. Since
1036tuples are immutable, the rules for literals apply here.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001037
1038(Note that tuples are not formed by the parentheses, but rather by use
1039of the comma operator. The exception is the empty tuple, for which
1040parentheses {\em are} required -- allowing unparenthesized ``nothing''
1041in expressions would causes ambiguities and allow common typos to
1042pass uncaught.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001043
1044\subsection{List displays}
1045
Guido van Rossum670e5a01992-01-17 14:03:20 +00001046A list display is a possibly empty series of conditions enclosed in
1047square brackets:
1048
1049\begin{verbatim}
1050list_display: "[" [condition_list] "]"
1051\end{verbatim}
1052
Guido van Rossumf2612d11991-11-21 13:53:03 +00001053A list display yields a new list object.
1054
1055If it has no condition list, the list object has no items.
1056Otherwise, the elements of the condition list are evaluated
1057from left to right and inserted in the list object in that order.
1058
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001059\subsection{Dictionary displays} \label{dict}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001060
Guido van Rossum670e5a01992-01-17 14:03:20 +00001061A dictionary display is a possibly empty series of key/datum pairs
1062enclosed in curly braces:
1063
1064\begin{verbatim}
1065dict_display: "{" [key_datum_list] "}"
1066key_datum_list: [key_datum ("," key_datum)* [","]
1067key_datum: condition ":" condition
1068\end{verbatim}
1069
Guido van Rossumf2612d11991-11-21 13:53:03 +00001070A dictionary display yields a new dictionary object.
1071
Guido van Rossum670e5a01992-01-17 14:03:20 +00001072The key/datum pairs are evaluated from left to right to define the
1073entries of the dictionary: each key object is used as a key into the
1074dictionary to store the corresponding datum.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001075
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001076Keys must be strings, otherwise a \verb\TypeError\ exception is raised.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001077Clashes between duplicate keys are not detected; the last datum
1078(textually rightmost in the display) stored for a given key value
1079prevails.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001080
1081\subsection{String conversions}
1082
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001083A string conversion is a condition list enclosed in reverse (or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001084backward) quotes:
1085
1086\begin{verbatim}
1087string_conversion: "`" condition_list "`"
1088\end{verbatim}
1089
Guido van Rossumf2612d11991-11-21 13:53:03 +00001090A string conversion evaluates the contained condition list and converts the
1091resulting object into a string according to rules specific to its type.
1092
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001093If the object is a string, a number, \verb\None\, or a tuple, list or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001094dictionary containing only objects whose type is one of these, the
1095resulting string is a valid Python expression which can be passed to
1096the built-in function \verb\eval()\ to yield an expression with the
Guido van Rossumf2612d11991-11-21 13:53:03 +00001097same value (or an approximation, if floating point numbers are
1098involved).
1099
1100(In particular, converting a string adds quotes around it and converts
1101``funny'' characters to escape sequences that are safe to print.)
1102
Guido van Rossum670e5a01992-01-17 14:03:20 +00001103It is illegal to attempt to convert recursive objects (e.g., lists or
1104dictionaries that contain a reference to themselves, directly or
1105indirectly.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001106
1107\section{Primaries}
1108
1109Primaries represent the most tightly bound operations of the language.
1110Their syntax is:
1111
1112\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001113primary: atom | attributeref | subscription | slicing | call
Guido van Rossumf2612d11991-11-21 13:53:03 +00001114\end{verbatim}
1115
1116\subsection{Attribute references}
1117
Guido van Rossum670e5a01992-01-17 14:03:20 +00001118An attribute reference is a primary followed by a period and a name:
1119
1120\begin{verbatim}
1121attributeref: primary "." identifier
1122\end{verbatim}
1123
1124The primary must evaluate to an object of a type that supports
1125attribute references, e.g., a module or a list. This object is then
1126asked to produce the attribute whose name is the identifier. If this
1127attribute is not available, the exception \verb\AttributeError\ is
1128raised. Otherwise, the type and value of the object produced is
1129determined by the object. Multiple evaluations of the same attribute
1130reference may yield different objects.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001131
1132\subsection{Subscriptions}
1133
Guido van Rossum670e5a01992-01-17 14:03:20 +00001134A subscription selects an item of a sequence or mapping object:
1135
1136\begin{verbatim}
1137subscription: primary "[" condition "]"
1138\end{verbatim}
1139
1140The primary must evaluate to an object of a sequence or mapping type.
1141
1142If it is a mapping, the condition must evaluate to an object whose
1143value is one of the keys of the mapping, and the subscription selects
1144the value in the mapping that corresponds to that key.
1145
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001146If it is a sequence, the condition must evaluate to a plain integer.
1147If this value is negative, the length of the sequence is added to it
1148(so that, e.g., \verb\x[-1]\ selects the last item of \verb\x\.)
1149The resulting value must be a nonnegative integer smaller than the
1150number of items in the sequence, and the subscription selects the item
1151whose index is that value (counting from zero).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001152
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001153A string's items are characters. A character is not a separate data
Guido van Rossum670e5a01992-01-17 14:03:20 +00001154type but a string of exactly one character.
1155
Guido van Rossumf2612d11991-11-21 13:53:03 +00001156\subsection{Slicings}
1157
Guido van Rossum670e5a01992-01-17 14:03:20 +00001158A slicing selects a range of items in a sequence object:
1159
1160\begin{verbatim}
1161slicing: primary "[" [condition] ":" [condition] "]"
1162\end{verbatim}
1163
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001164The primary must evaluate to a sequence object. The lower and upper
1165bound expressions, if present, must evaluate to plain integers;
1166defaults are zero and the sequence's length, respectively. If either
1167bound is negative, the sequence's length is added to it. The slicing
1168now selects all items with index $k$ such that $i <= k < j$ where $i$
1169and $j$ are the specified lower and upper bounds. This may be an
1170empty sequence. It is not an error if $i$ or $j$ lie outside the
1171range of valid indexes (such items don't exist so they aren't
1172selected).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001173
1174\subsection{Calls}
1175
1176A call calls a function with a possibly empty series of arguments:
1177
1178\begin{verbatim}
1179call: primary "(" [condition_list] ")"
1180\end{verbatim}
1181
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001182The primary must evaluate to a callable object (user-defined
1183functions, built-in functions, methods of built-in objects, class
1184objects, and methods of class instances are callable). If it is a
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001185class, the argument list must be empty; otherwise, the arguments are
1186evaluated.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001187
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001188A call always returns some value, possibly \verb\None\, unless it
1189raises an exception. How this value is computed depends on the type
1190of the callable object. If it is:
1191
1192\begin{description}
1193
1194\item[a user-defined function:] the code block for the function is
1195executed, passing it the argument list. The first thing the code
1196block will do is bind the formal parameters to the arguments. When
1197the code block executes a \verb\return\ statement, this specifies the
1198return value of the function call.
1199
1200\item[a built-in function or method:] the result is up to the
1201interpreter; see the library reference manual for the descriptions of
1202built-in functions and methods.
1203
1204\item[a class object:] a new instance of that class is returned.
1205
1206\item[a class instance method:] the corresponding user-defined
1207function is called, with an argument list that is one longer than the
1208argument list of the call: the instance becomes the first argument.
1209
1210\end{description}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001211
Guido van Rossumf2612d11991-11-21 13:53:03 +00001212\section{Factors}
1213
1214Factors represent the unary numeric operators.
1215Their syntax is:
1216
1217\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001218factor: primary | "-" factor | "+" factor | "~" factor
Guido van Rossumf2612d11991-11-21 13:53:03 +00001219\end{verbatim}
1220
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001221The unary \verb\"-"\ operator yields the negative of its
1222numeric argument.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001223
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001224The unary \verb\"+"\ operator yields its numeric argument unchanged.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001225
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001226The unary \verb\"~"\ operator yields the bit-wise negation of its
1227plain or long integer argument. The bit-wise negation negation of
1228\verb\x\ is defined as \verb\-(x+1)\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001229
1230In all three cases, if the argument does not have the proper type,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001231a \verb\TypeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001232
1233\section{Terms}
1234
1235Terms represent the most tightly binding binary operators:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001236%
Guido van Rossumf2612d11991-11-21 13:53:03 +00001237\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001238term: factor | term "*" factor | term "/" factor | term "%" factor
Guido van Rossumf2612d11991-11-21 13:53:03 +00001239\end{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001240%
1241The \verb\"*"\ (multiplication) operator yields the product of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001242arguments. The arguments must either both be numbers, or one argument
1243must be a plain integer and the other must be a sequence. In the
1244former case, the numbers are converted to a common type and then
1245multiplied together. In the latter case, sequence repetition is
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001246performed; a negative repetition factor yields an empty sequence.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001247
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001248The \verb\"/"\ (division) operator yields the quotient of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001249arguments. The numeric arguments are first converted to a common
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001250type. Plain or long integer division yields an integer of the same
1251type; the result is that of mathematical division with the `floor'
1252function applied to the result. Division by zero raises the
1253\verb\ZeroDivisionError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001254
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001255The \verb\"%"\ (modulo) operator yields the remainder from the
Guido van Rossum670e5a01992-01-17 14:03:20 +00001256division of the first argument by the second. The numeric arguments
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001257are first converted to a common type. A zero right argument raises the
1258\verb\ZeroDivisionError\ exception. The arguments may be floating point
1259numbers, e.g., \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo operator
Guido van Rossum670e5a01992-01-17 14:03:20 +00001260always yields a result with the same sign as its second operand (or
1261zero); the absolute value of the result is strictly smaller than the
1262second operand.
1263
1264The integer division and modulo operators are connected by the
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001265following identity: \verb\x == (x/y)*y + (x%y)\.
1266Integer division and modulo are also connected with the built-in
1267function \verb\divmod()\: \verb\divmod(x, y) == (x/y, x%y)\.
1268These identities don't hold for floating point numbers; there a
1269similar identity holds where \verb\x/y\ is replaced by
1270\verb\floor(x/y)\).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001271
1272\section{Arithmetic expressions}
1273
1274\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001275arith_expr: term | arith_expr "+" term | arith_expr "-" term
Guido van Rossumf2612d11991-11-21 13:53:03 +00001276\end{verbatim}
1277
Guido van Rossum670e5a01992-01-17 14:03:20 +00001278The \verb|"+"| operator yields the sum of its arguments. The
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001279arguments must either both be numbers, or both sequences of the same
1280type. In the former case, the numbers are converted to a common type
1281and then added together. In the latter case, the sequences are
1282concatenated.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001283
Guido van Rossum743d1e71992-01-07 16:43:53 +00001284The \verb|"-"| operator yields the difference of its arguments.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001285The numeric arguments are first converted to a common type.
1286
1287\section{Shift expressions}
1288
1289\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001290shift_expr: arith_expr | shift_expr ( "<<" | ">>" ) arith_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001291\end{verbatim}
1292
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001293These operators accept plain or long integers as arguments. The
1294arguments are converted to a common type. They shift the first
1295argument to the left or right by the number of bits given by the
1296second argument.
1297
1298A right shift by $n$ bits is defined as division by $2^n$. A left
1299shift by $n$ bits is defined as multiplication with $2^n$ without
1300overflow check; for plain integers this drops bits if the result is
1301not less than $2^{31} - 1$ in absolute value.
1302
1303Negative shift counts raise a \verb\ValueError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001304
1305\section{Bitwise AND expressions}
1306
1307\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001308and_expr: shift_expr | and_expr "&" shift_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001309\end{verbatim}
1310
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001311This operator yields the bitwise AND of its arguments, which must be
1312plain or long integers. The arguments are converted to a common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001313
1314\section{Bitwise XOR expressions}
1315
1316\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001317xor_expr: and_expr | xor_expr "^" and_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001318\end{verbatim}
1319
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001320This operator yields the bitwise exclusive OR of its arguments, which
1321must be plain or long integers. The arguments are converted to a
1322common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001323
1324\section{Bitwise OR expressions}
1325
1326\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001327or_expr: xor_expr | or_expr "|" xor_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001328\end{verbatim}
1329
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001330This operator yields the bitwise OR of its arguments, which must be
1331plain or long integers. The arguments are converted to a common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001332
1333\section{Comparisons}
1334
1335\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001336comparison: or_expr (comp_operator or_expr)*
Guido van Rossum743d1e71992-01-07 16:43:53 +00001337comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001338\end{verbatim}
1339
1340Comparisons yield integer value: 1 for true, 0 for false.
1341
1342Comparisons can be chained arbitrarily,
1343e.g., $x < y <= z$ is equivalent to
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001344$x < y$ \verb\and\ $y <= z$, except that $y$ is evaluated only once
Guido van Rossumf2612d11991-11-21 13:53:03 +00001345(but in both cases $z$ is not evaluated at all when $x < y$ is
1346found to be false).
1347
1348Formally, $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 +00001349$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 +00001350$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
1351
1352Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
1353between $e_0$ and $e_2$, e.g., $x < y > z$ is perfectly legal.
1354
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001355The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with
1356C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below
1357\verb\<>\ is also implied.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001358
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001359The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
Guido van Rossumf2612d11991-11-21 13:53:03 +00001360the values of two objects. The objects needn't have the same type.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001361If both are numbers, they are coverted to a common type. Otherwise,
1362objects of different types {\em always} compare unequal, and are
1363ordered consistently but arbitrarily.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001364
1365(This unusual
1366definition of comparison is done to simplify the definition of
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001367operations like sorting and the \verb\in\ and \verb\not in\ operators.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001368
1369Comparison of objects of the same type depends on the type:
1370
1371\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001372
1373\item
1374Numbers are compared arithmetically.
1375
1376\item
1377Strings are compared lexicographically using the numeric equivalents
1378(the result of the built-in function \verb\ord\) of their characters.
1379
1380\item
1381Tuples and lists are compared lexicographically using comparison of
1382corresponding items.
1383
1384\item
1385Mappings (dictionaries) are compared through lexicographic
1386comparison of their sorted (key, value) lists.%
1387\footnote{This is expensive since it requires sorting the keys first,
1388but about the only sensible definition. It was tried to compare
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001389dictionaries using the rule below for most other types, but this gave
1390surprises in cases like \verb|if d == {}: ...|.}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001391
1392\item
1393Most other types compare unequal unless they are the same object;
1394the choice whether one object is considered smaller or larger than
1395another one is made arbitrarily but consistently within one
1396execution of a program.
1397
Guido van Rossumf2612d11991-11-21 13:53:03 +00001398\end{itemize}
1399
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001400The operators \verb\in\ and \verb\not in\ test for sequence
1401membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and
1402only if there exists an index $i$ such that $x = y[i]$.
1403$x ~\verb\not in\~ y$ yields the inverse truth value. The exception
1404\verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is
1405a string and $x$ is not a string of length one.%
1406\footnote{The latter restriction is sometimes a nuisance.}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001407
1408The operators \verb\is\ and \verb\is not\ compare object identity:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001409$x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same
1410object. $x ~\verb\is not\~ y$ yields the inverse truth value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001411
1412\section{Boolean operators}
1413
1414\begin{verbatim}
1415condition: or_test
Guido van Rossum743d1e71992-01-07 16:43:53 +00001416or_test: and_test | or_test "or" and_test
1417and_test: not_test | and_test "and" not_test
1418not_test: comparison | "not" not_test
Guido van Rossumf2612d11991-11-21 13:53:03 +00001419\end{verbatim}
1420
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001421In the context of Boolean operators, and also when conditions are used
1422by control flow statements, the following values are interpreted as
1423false: \verb\None\, numeric zero of all types, empty sequences
1424(strings, tuples and lists), and empty mappings (dictionaries). All
1425other values are interpreted as true.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001426
1427The operator \verb\not\ yields 1 if its argument is false, 0 otherwise.
1428
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001429The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001430$x$ is returned; otherwise, $y$ is evaluated and returned.
1431
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001432The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001433$x$ is returned; otherwise, $y$ is evaluated and returned.
1434
1435(Note that \verb\and\ and \verb\or\ do not restrict the value and type
1436they return to 0 and 1, but rather return the last evaluated argument.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001437This is sometimes useful, e.g., if \verb\s\ is a string, which should be
1438replaced by a default value if it is empty, \verb\s or 'foo'\
Guido van Rossumf2612d11991-11-21 13:53:03 +00001439returns the desired value. Because \verb\not\ has to invent a value
1440anyway, it does not bother to return a value of the same type as its
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001441argument, so \verb\not 'foo'\ yields \verb\0\, not \verb\''\.)
1442
1443\section{Expression lists and condition lists}
1444
1445\begin{verbatim}
1446expr_list: or_expr ("," or_expr)* [","]
1447cond_list: condition ("," condition)* [","]
1448\end{verbatim}
1449
1450The only difference between expression lists and condition lists is
1451the lowest priority of operators that can be used in them without
1452being enclosed in parentheses; condition lists allow all operators,
1453while expression lists don't allow comparisons and Boolean operators
1454(they do allow bitwise and shift operators though).
1455
1456Expression lists are used in expression statements and assignments;
1457condition lists are used everywhere else.
1458
1459An expression (condition) list containing at least one comma yields a
1460tuple. The length of the tuple is the number of expressions
1461(conditions) in the list. The expressions (conditions) are evaluated
1462from left to right.
1463
1464The trailing comma is required only to create a single tuple (a.k.a. a
1465{\em singleton}); it is optional in all other cases. A single
1466expression (condition) without a trailing comma doesn't create a
1467tuple, but rather yields the value of that expression (condition).
1468
1469To create an empty tuple, use an empty pair of parentheses: \verb\()\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001470
1471\chapter{Simple statements}
1472
1473Simple statements are comprised within a single logical line.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001474Several simple statements may occur on a single line separated
Guido van Rossumf2612d11991-11-21 13:53:03 +00001475by semicolons. The syntax for simple statements is:
1476
1477\begin{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001478simple_stmt: expression_stmt
1479 | assignment
1480 | pass_stmt
1481 | del_stmt
1482 | print_stmt
1483 | return_stmt
1484 | raise_stmt
1485 | break_stmt
1486 | continue_stmt
1487 | import_stmt
Guido van Rossum743d1e71992-01-07 16:43:53 +00001488 | global_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001489\end{verbatim}
1490
1491\section{Expression statements}
1492
1493\begin{verbatim}
1494expression_stmt: expression_list
1495\end{verbatim}
1496
1497An expression statement evaluates the expression list (which may
1498be a single expression).
1499If the value is not \verb\None\, it is converted to a string
1500using the rules for string conversions, and the resulting string
1501is written to standard output on a line by itself.
1502
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001503(The exception for \verb\None\ is made so that procedure calls, which
1504are syntactically equivalent to expressions, do not cause any output.
1505A tuple with only \verb\None\ items is written normally.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001506
1507\section{Assignments}
1508
1509\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001510assignment: (target_list "=")+ expression_list
Guido van Rossum743d1e71992-01-07 16:43:53 +00001511target_list: target ("," target)* [","]
1512target: identifier | "(" target_list ")" | "[" target_list "]"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001513 | attributeref | subscription | slicing
1514\end{verbatim}
1515
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001516(See the section on primaries for the syntax definition of the last
Guido van Rossumf2612d11991-11-21 13:53:03 +00001517three symbols.)
1518
1519An assignment evaluates the expression list (remember that this can
1520be a single expression or a comma-separated list,
1521the latter yielding a tuple)
1522and assigns the single resulting object to each of the target lists,
1523from left to right.
1524
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001525Assignment is defined recursively depending on the form of the target.
1526When a target is part of a mutable object (an attribute reference,
1527subscription or slicing), the mutable object must ultimately perform
1528the assignment and decide about its validity, and may raise an
1529exception if the assignment is unacceptable. The rules observed by
1530various types and the exceptions raised are given with the definition
1531of the object types (some of which are defined in the library
1532reference).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001533
1534Assignment of an object to a target list is recursively
1535defined as follows.
1536
1537\begin{itemize}
1538\item
1539If the target list contains no commas (except in nested constructs):
1540the object is assigned to the single target contained in the list.
1541
1542\item
1543If the target list contains commas (that are not in nested constructs):
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001544the object must be a tuple with the same number of items
Guido van Rossumf2612d11991-11-21 13:53:03 +00001545as the list contains targets, and the items are assigned, from left
1546to right, to the corresponding targets.
1547
1548\end{itemize}
1549
1550Assignment of an object to a (non-list)
1551target is recursively defined as follows.
1552
1553\begin{itemize}
1554
1555\item
1556If the target is an identifier (name):
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001557\begin{itemize}
1558\item
1559If the name does not occur in a \verb\global\ statement in the current
1560code block: the object is bound to that name in the current local
1561name space.
1562\item
1563Otherwise: the object is bound to that name in the current global name
1564space.
1565\end{itemize}
1566A previous binding of the same name in the same name space is undone.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001567
1568\item
1569If the target is a target list enclosed in parentheses:
1570the object is assigned to that target list.
1571
1572\item
1573If the target is a target list enclosed in square brackets:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001574the object must be a list with the same number of items
Guido van Rossumf2612d11991-11-21 13:53:03 +00001575as the target list contains targets,
1576and the list's items are assigned, from left to right,
1577to the corresponding targets.
1578
1579\item
1580If the target is an attribute reference:
1581The primary expression in the reference is evaluated.
1582It should yield an object with assignable attributes;
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001583if this is not the case, \verb\TypeError\ is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001584That object is then asked to assign the assigned object
1585to the given attribute; if it cannot perform the assignment,
1586it raises an exception.
1587
1588\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001589If the target is a subscription: The primary expression in the
1590reference is evaluated. It should yield either a mutable sequence
1591(list) object or a mapping (dictionary) object. Next, the subscript
1592expression is evaluated.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001593
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001594If the primary is a sequence object, the subscript must yield a plain
1595integer. If it is negative, the sequence's length is added to it.
1596The resulting value must be a nonnegative integer less than the
1597sequence's length, and the sequence is asked to assign the assigned
1598object to its item with that index. If the index is out of range,
1599\verb\IndexError\ is raised (assignment to a subscripted sequence
1600cannot add new items to a list).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001601
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001602If the primary is a mapping object, the subscript must have a type
1603compatible with the mapping's key type, and the mapping is then asked
1604to to create a key/datum pair which maps the subscript to the assigned
1605object. This can either replace an existing key/value pair with the
1606same key value, or insert a new key/value pair (if no key with the
1607same value existed).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001608
1609\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001610If the target is a slicing: The primary expression in the reference is
1611evaluated. It should yield a mutable sequence (list) object. The
1612assigned object should be a sequence object of the same type. Next,
1613the lower and upper bound expressions are evaluated, insofar they are
1614present; defaults are zero and the sequence's length. The bounds
1615should evaluate to (small) integers. If either bound is negative, the
1616sequence's length is added to it. The resulting bounds are clipped to
1617lie between zero and the sequence's length, inclusive. Finally, the
1618sequence object is asked to replace the items indicated by the slice
1619with the items of the assigned sequence. This may change the
1620sequence's length, if it allows it.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001621
1622\end{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001623
Guido van Rossumf2612d11991-11-21 13:53:03 +00001624(In the original implementation, the syntax for targets is taken
1625to be the same as for expressions, and invalid syntax is rejected
1626during the code generation phase, causing less detailed error
1627messages.)
1628
Guido van Rossum68c172e1992-01-21 11:34:56 +00001629\section{The {\tt pass} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001630
1631\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001632pass_stmt: "pass"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001633\end{verbatim}
1634
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001635\verb\pass\ is a null operation -- when it is executed, nothing
1636happens. It is useful as a placeholder when a statement is
1637required syntactically, but no code needs to be executed, for example:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001638
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001639\begin{verbatim}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001640def f(arg): pass # a function that does nothing (yet)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001641
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001642class C: pass # an class with no methods (yet)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001643\end{verbatim}
1644
Guido van Rossum68c172e1992-01-21 11:34:56 +00001645\section{The {\tt del} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001646
1647\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001648del_stmt: "del" target_list
Guido van Rossumf2612d11991-11-21 13:53:03 +00001649\end{verbatim}
1650
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001651Deletion is recursively defined very similar to the way assignment is
1652defined. Rather that spelling it out in full details, here are some
1653hints.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001654
1655Deletion of a target list recursively deletes each target,
1656from left to right.
1657
1658Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001659from the local or global name space, depending on whether the name
1660occurs in a \verb\global\ statement in the same code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001661
1662Deletion of attribute references, subscriptions and slicings
1663is passed to the primary object involved; deletion of a slicing
1664is in general equivalent to assignment of an empty slice of the
1665right type (but even this is determined by the sliced object).
1666
Guido van Rossum68c172e1992-01-21 11:34:56 +00001667\section{The {\tt print} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001668
1669\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001670print_stmt: "print" [ condition ("," condition)* [","] ]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001671\end{verbatim}
1672
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001673\verb\print\ evaluates each condition in turn and writes the resulting
1674object to standard output (see below). If an object is not a string,
1675it is first converted to a string using the rules for string
1676conversions. The (resulting or original) string is then written. A
1677space is written before each object is (converted and) written, unless
1678the output system believes it is positioned at the beginning of a
1679line. This is the case: (1) when no characters have yet been written
1680to standard output; or (2) when the last character written to standard
1681output is \verb/\n/; or (3) when the last write operation on standard
1682output was not a \verb\print\ statement. (In some cases it may be
1683functional to write an empty string to standard output for this
1684reason.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001685
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001686A \verb/"\n"/ character is written at the end, unless the \verb\print\
1687statement ends with a comma. This is the only action if the statement
1688contains just the keyword \verb\print\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001689
1690Standard output is defined as the file object named \verb\stdout\
1691in the built-in module \verb\sys\. If no such object exists,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001692or if it is not a writable file, a \verb\RuntimeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001693(The original implementation attempts to write to the system's original
1694standard output instead, but this is not safe, and should be fixed.)
1695
Guido van Rossum68c172e1992-01-21 11:34:56 +00001696\section{The {\tt return} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001697
1698\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001699return_stmt: "return" [condition_list]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001700\end{verbatim}
1701
1702\verb\return\ may only occur syntactically nested in a function
1703definition, not within a nested class definition.
1704
1705If a condition list is present, it is evaluated, else \verb\None\
1706is substituted.
1707
1708\verb\return\ leaves the current function call with the condition
1709list (or \verb\None\) as return value.
1710
1711When \verb\return\ passes control out of a \verb\try\ statement
1712with a \verb\finally\ clause, that finally clause is executed
1713before really leaving the function.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001714
Guido van Rossum68c172e1992-01-21 11:34:56 +00001715\section{The {\tt raise} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001716
1717\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001718raise_stmt: "raise" condition ["," condition]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001719\end{verbatim}
1720
1721\verb\raise\ evaluates its first condition, which must yield
1722a string object. If there is a second condition, this is evaluated,
1723else \verb\None\ is substituted.
1724
1725It then raises the exception identified by the first object,
1726with the second one (or \verb\None\) as its parameter.
1727
Guido van Rossum68c172e1992-01-21 11:34:56 +00001728\section{The {\tt break} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001729
1730\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001731break_stmt: "break"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001732\end{verbatim}
1733
1734\verb\break\ may only occur syntactically nested in a \verb\for\
1735or \verb\while\ loop, not nested in a function or class definition.
1736
1737It terminates the neares enclosing loop, skipping the optional
1738\verb\else\ clause if the loop has one.
1739
1740If a \verb\for\ loop is terminated by \verb\break\, the loop control
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001741target keeps its current value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001742
1743When \verb\break\ passes control out of a \verb\try\ statement
1744with a \verb\finally\ clause, that finally clause is executed
1745before really leaving the loop.
1746
Guido van Rossum68c172e1992-01-21 11:34:56 +00001747\section{The {\tt continue} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001748
1749\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001750continue_stmt: "continue"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001751\end{verbatim}
1752
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001753\verb\continue\ may only occur syntactically nested in a \verb\for\ or
1754\verb\while\ loop, not nested in a function or class definition, and
1755not nested in the \verb\try\ clause of a \verb\try\ statement with a
1756\verb\finally\ clause (it may occur nested in a \verb\except\ or
1757\verb\finally\ clause of a \verb\try\ statement though).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001758
1759It continues with the next cycle of the nearest enclosing loop.
1760
Guido van Rossum862c6f11992-01-29 14:47:05 +00001761\section{The {\tt import} statement} \label{import}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001762
1763\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001764import_stmt: "import" identifier ("," identifier)*
1765 | "from" identifier "import" identifier ("," identifier)*
1766 | "from" identifier "import" "*"
1767\end{verbatim}
1768
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001769Import statements are executed in two steps: (1) find a module, and
1770initialize it if necessary; (2) define a name or names in the local
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001771name space (of the scope where the \verb\import\ statement occurs).
1772The first form (without \verb\from\) repeats these steps for each
1773identifier in the list, the \verb\from\ form performs them once, with
1774the first identifier specifying the module name.
Guido van Rossum743d1e71992-01-07 16:43:53 +00001775
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001776The system maintains a table of modules that have been initialized,
1777indexed by module name. (The current implementation makes this table
1778accessible as \verb\sys.modules\.) When a module name is found in
1779this table, step (1) is finished. If not, a search for a module
1780definition is started. This first looks for a built-in module
1781definition, and if no built-in module if the given name is found, it
1782searches a user-specified list of directories for a file whose name is
1783the module name with extension \verb\".py"\. (The current
1784implementation uses the list of strings \verb\sys.path\ as the search
1785path; it is initialized from the shell environment variable
1786\verb\$PYTHONPATH\, with an installation-dependent default.)
1787
1788If a built-in module is found, its built-in initialization code is
1789executed and step (1) is finished. If no matching file is found,
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001790\verb\ImportError\ is raised. If a file is found, it is parsed,
1791yielding an executable code block. If a syntax error occurs,
1792\verb\SyntaxError\ is raised. Otherwise, an empty module of the given
1793name is created and inserted in the module table, and then the code
1794block is executed in the context of this module. Exceptions during
1795this execution terminate step (1).
1796
1797When step (1) finishes without raising an exception, step (2) can
1798begin.
1799
1800The first form of \verb\import\ statement binds the module name in the
1801local name space to the module object, and then goes on to import the
1802next identifier, if any. The \verb\from\ from does not bind the
1803module name: it goes through the list of identifiers, looks each one
1804of them up in the module found in step (1), and binds the name in the
1805local name space to the object thus found. If a name is not found,
1806\verb\ImportError\ is raised. If the list of identifiers is replaced
1807by a star (\verb\*\), all names defined in the module are bound,
1808except those beginning with an underscore(\verb\_\).
1809
1810Names bound by import statements may not occur in \verb\global\
1811statements in the same scope.
1812
1813The \verb\from\ form with \verb\*\ may only occur in a module scope.
1814
1815(The current implementation does not enforce the latter two
1816restrictions, but programs should not abuse this freedom, as future
1817implementations may enforce them or silently change the meaning of the
1818program.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001819
Guido van Rossum862c6f11992-01-29 14:47:05 +00001820\section{The {\tt global} statement} \label{global}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001821
1822\begin{verbatim}
1823global_stmt: "global" identifier ("," identifier)*
Guido van Rossumf2612d11991-11-21 13:53:03 +00001824\end{verbatim}
1825
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001826The \verb\global\ statement is a declaration which holds for the
1827entire current scope. It means that the listed identifiers are to be
1828interpreted as globals. While {\em using} global names is automatic
1829if they are not defined in the local scope, {\em assigning} to global
1830names would be impossible without \verb\global\.
1831
1832Names listed in a \verb\global\ statement must not be used in the same
1833scope before that \verb\global\ statement is executed.
1834
1835Name listed in a \verb\global\ statement must not be defined as formal
1836parameters or in a \verb\for\ loop control target, \verb\class\
1837definition, function definition, or \verb\import\ statement.
1838
1839(The current implementation does not enforce the latter two
1840restrictions, but programs should not abuse this freedom, as future
1841implementations may enforce them or silently change the meaning of the
1842program.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001843
1844\chapter{Compound statements}
1845
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001846Compound statements contain (groups of) other statements; they affect
1847or control the execution of those other statements in some way.
1848
1849The \verb\if\, \verb\while\ and \verb\for\ statements implement
1850traditional control flow constructs. \verb\try\ specifies exception
1851handlers and/or cleanup code for a group of statements. Function and
1852class definitions are also syntactically compound statements.
1853
1854Compound statements consist of one or more `clauses'. A clause
1855consists of a header and a `suite'. The clause headers of a
1856particular compound statement are all at the same indentation level;
1857all clauses begin with a uniquely identifying keyword and end with a
1858colon. A suite is a group of statements controlled by a clause. A
1859suite can be a bunch of semicolon-separated simple statements on the
1860same line as the header, following the colon, or it can be a list of
1861indented statements. Only the latter form of suite can contain nested
1862compound statements; the following is illegal (mostly because it
1863wouldn't be clear what to do with \verb\else\):
Guido van Rossumf2612d11991-11-21 13:53:03 +00001864
1865\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001866if test1: if test2: print x
Guido van Rossumf2612d11991-11-21 13:53:03 +00001867\end{verbatim}
1868
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001869Also note that the semicolon binds tighter that the colon in this
1870context (so to speak), so that in the following example, either all or
1871none of the \verb\print\ statements are executed:
1872
1873\begin{verbatim}
1874if some_test: print x; print y; print z
1875\end{verbatim}
1876
1877Summarizing:
1878
1879\begin{verbatim}
1880compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1881suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
1882statement: stmt_list NEWLINE | compound_stmt
1883stmt_list: simple_stmt (";" simple_stmt)* [";"]
1884\end{verbatim}
1885
1886Note that statements always ends in a \verb\NEWLINE\ possibly followed
1887by a \verb\DEDENT\.
1888
1889Also note that optional continuation clauses always begin with a
1890keyword that cannot start a statement, thus there are no ambiguities
1891(the `dangling \verb\else\' problem is solved in Python by requiring
1892nested \verb\if\ statements to be indented).
1893
1894The formatting of the grammar rules in the following section places
1895each clause on a separate line for clarity.
1896
Guido van Rossum68c172e1992-01-21 11:34:56 +00001897\section{The {\tt if} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001898
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001899The \verb\if\ statement is used for conditional execution:
1900
Guido van Rossumf2612d11991-11-21 13:53:03 +00001901\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001902if_stmt: "if" condition ":" suite
1903 ("elif" condition ":" suite)*
1904 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001905\end{verbatim}
1906
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001907It selects exactly one of the suites, by testing the conditions one by
1908one until one is true; then that suite is executed. If all conditions
1909are false, the suite of the \verb\else\ clause is executed, if present.
1910
Guido van Rossum68c172e1992-01-21 11:34:56 +00001911\section{The {\tt while} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001912
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001913The \verb\while\ statement is used for repeated execution as long as a
1914condition is true:
1915
Guido van Rossumf2612d11991-11-21 13:53:03 +00001916\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001917while_stmt: "while" condition ":" suite
1918 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001919\end{verbatim}
1920
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001921This repeatedly tests the condition and, if it is true, executes the
1922first suite; if the condition is false (which may be the first time it
1923is tested) the suite of the \verb\else\ clause is executed, if
1924present, and the loop terminates.
1925
1926A \verb\break\ statement executed in the first suite terminates the
1927loop without executing the \verb\else\ clause's suite. A
1928\verb\continue\ statement executed in the first suited skips the rest
1929of the suite and goes back to testing the condition.
1930
Guido van Rossum68c172e1992-01-21 11:34:56 +00001931\section{The {\tt for} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001932
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001933The \verb\for\ statement is used to iterate over the elements of a
1934sequence (string, tuple or list):
1935
Guido van Rossumf2612d11991-11-21 13:53:03 +00001936\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001937for_stmt: "for" target_list "in" condition_list ":" suite
1938 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001939\end{verbatim}
1940
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001941The suite is executed once for each item in the condition list, in the
1942order of ascending indices. Each item in turn is assigned to the
1943target list using the standard rules for assignments, and then the
1944suite is executed. When the list is exhausted (which is immediately
1945when the sequence is empty), the suite in the \verb\else\ clause is
1946executed, if present.
1947
1948A \verb\break\ statement executed in the first suite terminates the
1949loop without executing the \verb\else\ clause's suite. A
1950\verb\continue\ statement executed in the first suited skips the rest
1951of the suite and continues with the next item or with the \verb\else\
1952clause.
1953
1954The suite may assign to the variable(s) in the target list; this does
1955not affect the next item assigned to it.
1956
1957The target list are not deleted when the loop is finished (but if the
1958loop has executed 0 times it will not have been assigned to at all by
1959the loop).
1960
1961The built-in function \verb\range()\ returns a sequence of integers
1962suitable to emulate the effect of Pascal's \verb\for i := 1 to n do\.
1963
1964{\bf Warning:} There is a subtlety when the sequence is being modified
1965by the loop (this can only occur for lists). An internal counter is
1966used to keep track of which item is used next, and this is incremented
1967on each iteration. When this counter has reached the end of the
1968sequence the loop terminates. This means that if the suite deletes
1969the current (or a previous) item from the sequence, the next item will
1970be skipped (since it gets the index of the current item and this has
1971already been treated). Likewise, if the suite inserts an item in the
1972sequence before the current item, the current item will be treated
1973again the next time through the loop. This can lead to nasty bugs
1974that can be avoided by making a temporary copy using the \
1975
Guido van Rossum68c172e1992-01-21 11:34:56 +00001976\section{The {\tt try} statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001977
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001978The \verb\try\ statement specifies exception handlers and/or cleanup
1979code for a group of statements:
1980
Guido van Rossumf2612d11991-11-21 13:53:03 +00001981\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001982try_stmt: "try" ":" suite
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001983 ("except" condition ["," target] ":" suite)*
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001984 ["except" ":" suite]
Guido van Rossum743d1e71992-01-07 16:43:53 +00001985 ["finally" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001986\end{verbatim}
1987
Guido van Rossum255ad6e1992-01-28 18:10:46 +00001988There are really two forms: \verb\try...except\ and
1989\verb\try...finally\. A \verb\try\ statement with both types of
1990clauses is equivalent to a \verb\try...finally\ statement with a
1991\verb\try...except\ statement in its \verb\try\ clause. A \verb\try\
1992statement with neither a \verb\except\ clause nor a \verb\finally\
1993clause just executes the suite of statements in its \verb\try\ clause.
1994
1995The \verb\try...except\ form specifies one or more exception handlers.
1996When no exception occurs in the \verb\try\ clause, no exception
1997handler is executed. When an exception occurs in the \verb\try\
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001998suite, a search for an exception handler is started. This inspects
1999the except clauses (exception handlers) in turn until one is found
2000that matches the exception. A condition-less except clause (which
2001must be last) matches any exception. For except clause with a
2002condition, that condition is evaluated, and the clause matches the
2003exception if the resulting object is ``compatible'' with the
2004exception. An object is compatible with an exception if it is either
2005the object that identifies the exception or it is a tuple containing
2006an item that is compatible with the exception.
2007
2008If no except clause matches the exception, the search for an exception
2009handler continues in the surrounding code and on the invocation stack.
2010
2011If the evaluation of a condition in the header of an except clause
2012raises an exception, the original search for a handler is cancelled
2013and a search starts for the new exception in the surrounding code and
2014on the call stack.
2015
2016When a matching except clause is found in a try statement, the
2017exception's parameter is assigned to the target specified in the
2018except clause (if present), and the except clause's suite is executed.
2019When the end of this suite is reached, execution continues normally
2020at the point following the entire try statement. (This means that if
2021two nested handlers exist for the same exception, and the exception
2022occurs in the try clause of the inner handler, the outer handler will
2023not notice the exception.)
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002024
2025The \verb\try...finally\ form specifies a `cleanup' handler. The
2026\verb\try\ clause is executed. When no exception occurs, the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002027\verb\finally\ clause is executed. When an exception occurs in the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002028\verb\try\ clause, the exception is temporarily saved, the
2029\verb\finally\ clause is executed, and then the saved exception is
2030re-raised. If the \verb\finally\ clause raises another exception or
2031executes a \verb\return\, \verb\break\ or \verb\continue\ statement,
2032the saved exception is lost.
2033
2034When a \verb\return\ or \verb\break\ statement is executed in the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002035\verb\try\ suite of a \verb\try...finally\ statement, the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002036\verb\finally\ clause is also executed `on the way out'. A
2037\verb\continue\ statement is illegal in the \verb\try\ clause (the
2038reason is a problem with the current implementation -- this
2039restriction may be lifted in the future).
2040
Guido van Rossum862c6f11992-01-29 14:47:05 +00002041\section{Function definitions} \label{function}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002042
Guido van Rossum862c6f11992-01-29 14:47:05 +00002043XXX
Guido van Rossumf2612d11991-11-21 13:53:03 +00002044
2045\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002046funcdef: "def" identifier "(" [parameter_list] ")" ":" suite
2047parameter_list: parameter ("," parameter)*
2048parameter: identifier | "(" parameter_list ")"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002049\end{verbatim}
2050
Guido van Rossum862c6f11992-01-29 14:47:05 +00002051XXX
2052
2053\section{Class definitions} \label{class}
2054
2055XXX
Guido van Rossumf2612d11991-11-21 13:53:03 +00002056
2057\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002058classdef: "class" identifier [inheritance] ":" suite
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002059inheritance: "(" condition_list ")"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002060\end{verbatim}
2061
Guido van Rossum862c6f11992-01-29 14:47:05 +00002062XXX
2063
2064\section{P.M.}
2065
Guido van Rossumf2612d11991-11-21 13:53:03 +00002066XXX Syntax for scripts, modules
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002067XXX Syntax for interactive input, eval, exec, execfile, input
Guido van Rossum743d1e71992-01-07 16:43:53 +00002068XXX New definition of expressions (as conditions)
Guido van Rossumf2612d11991-11-21 13:53:03 +00002069
2070\end{document}