blob: f4eb46e9ed37e6ee3cd517b9a9738f6cfb64153e [file] [log] [blame]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001% Format this file with latex.
Guido van Rossum7b632a61992-01-16 17:49:21 +00002
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00003\documentstyle[11pt,myformat]{report}
Guido van Rossumf2612d11991-11-21 13:53:03 +00004
5\title{\bf
6 Python Reference Manual \\
7 {\em Incomplete Draft}
8}
9
10\author{
11 Guido van Rossum \\
12 Dept. CST, CWI, Kruislaan 413 \\
13 1098 SJ Amsterdam, The Netherlands \\
14 E-mail: {\tt guido@cwi.nl}
15}
16
17\begin{document}
18
19\pagenumbering{roman}
20
21\maketitle
22
23\begin{abstract}
24
25\noindent
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000026Python is a simple, yet powerful, interpreted programming language
27that bridges the gap between C and shell programming, and is thus
28ideally suited for ``throw-away programming'' and rapid prototyping.
29Its syntax is put together from constructs borrowed from a variety of
30other languages; most prominent are influences from ABC, C, Modula-3
31and Icon.
Guido van Rossumf2612d11991-11-21 13:53:03 +000032
33The Python interpreter is easily extended with new functions and data
34types implemented in C. Python is also suitable as an extension
35language for highly customizable C applications such as editors or
36window managers.
37
38Python is available for various operating systems, amongst which
39several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S.,
40and MS-DOS.
41
42This reference manual describes the syntax and ``core semantics'' of
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000043the language. It is terse, but attempts to be exact and complete.
44The semantics of non-essential built-in object types and of the
45built-in functions and modules are described in the {\em Python
46Library Reference}. For an informal introduction to the language, see
47the {\em Python Tutorial}.
Guido van Rossumf2612d11991-11-21 13:53:03 +000048
49\end{abstract}
50
51\pagebreak
52
Guido van Rossum670e5a01992-01-17 14:03:20 +000053{
54\parskip = 0mm
Guido van Rossumf2612d11991-11-21 13:53:03 +000055\tableofcontents
Guido van Rossum670e5a01992-01-17 14:03:20 +000056}
Guido van Rossumf2612d11991-11-21 13:53:03 +000057
58\pagebreak
59
60\pagenumbering{arabic}
61
62\chapter{Introduction}
63
64This reference manual describes the Python programming language.
65It is not intended as a tutorial.
66
Guido van Rossum743d1e71992-01-07 16:43:53 +000067While I am trying to be as precise as possible, I chose to use English
68rather than formal specifications for everything except syntax and
69lexical analysis. This should make the document better understandable
70to the average reader, but will leave room for ambiguities.
71Consequently, if you were coming from Mars and tried to re-implement
Guido van Rossum7b632a61992-01-16 17:49:21 +000072Python from this document alone, you might have to guess things and in
73fact you would be implementing quite a different language.
74On the other hand, if you are using
Guido van Rossum743d1e71992-01-07 16:43:53 +000075Python and wonder what the precise rules about a particular area of
Guido van Rossum7b632a61992-01-16 17:49:21 +000076the language are, you should definitely be able to find it here.
Guido van Rossum743d1e71992-01-07 16:43:53 +000077
78It is dangerous to add too many implementation details to a language
79reference document -- the implementation may change, and other
80implementations of the same language may work differently. On the
81other hand, there is currently only one Python implementation, and
Guido van Rossum7b632a61992-01-16 17:49:21 +000082its particular quirks are sometimes worth being mentioned, especially
83where the implementation imposes additional limitations.
Guido van Rossum743d1e71992-01-07 16:43:53 +000084
85Every Python implementation comes with a number of built-in and
86standard modules. These are not documented here, but in the separate
87{\em Python Library Reference} document. A few built-in modules are
88mentioned when they interact in a significant way with the language
89definition.
90
Guido van Rossum670e5a01992-01-17 14:03:20 +000091\section{Warning}
92
93This version of the manual is incomplete. Sections that still need to
94be written or need considerable work are marked with ``XXX''.
95
Guido van Rossum743d1e71992-01-07 16:43:53 +000096\section{Notation}
97
98The descriptions of lexical analysis and syntax use a modified BNF
99grammar notation. This uses the following style of definition:
100
101\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000102name: lc_letter (lc_letter | "_")*
103lc_letter: "a"..."z"
Guido van Rossum743d1e71992-01-07 16:43:53 +0000104\end{verbatim}
105
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000106The first line says that a \verb\name\ is an \verb\lc_letter\ followed by
107a sequence of zero or more \verb\lc_letter\s and underscores. An
108\verb\lc_letter\ in turn is any of the single characters `a' through `z'.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000109(This rule is actually adhered to for the names defined in syntax and
110grammar rules in this document.)
111
112Each rule begins with a name (which is the name defined by the rule)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000113and a colon. A vertical bar
Guido van Rossum7b632a61992-01-16 17:49:21 +0000114(\verb\|\) is used to separate alternatives; it is the least binding
115operator in this notation. A star (\verb\*\) means zero or more
116repetitions of the preceding item; likewise, a plus (\verb\+\) means
117one or more repetitions, and a question mark (\verb\?\) zero or one
118(in other words, the preceding item is optional). These three
119operators bind as tightly as possible; parentheses are used for
Guido van Rossum743d1e71992-01-07 16:43:53 +0000120grouping. Literal strings are enclosed in double quotes. White space
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000121is only meaningful to separate tokens. Rules are normally contained
122on a single line; rules with many alternatives may be formatted
123alternatively with each line after the first beginning with a
124vertical bar.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000125
126In lexical definitions (as the example above), two more conventions
127are used: Two literal characters separated by three dots mean a choice
128of any single character in the given (inclusive) range of ASCII
129characters. A phrase between angular brackets (\verb\<...>\) gives an
130informal description of the symbol defined; e.g., this could be used
131to describe the notion of `control character' if needed.
132
Guido van Rossum7b632a61992-01-16 17:49:21 +0000133Even though the notation used is almost the same, there is a big
Guido van Rossum743d1e71992-01-07 16:43:53 +0000134difference between the meaning of lexical and syntactic definitions:
135a lexical definition operates on the individual characters of the
136input source, while a syntax definition operates on the stream of
137tokens generated by the lexical analysis.
138
Guido van Rossumf2612d11991-11-21 13:53:03 +0000139\chapter{Lexical analysis}
140
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000141A Python program is read by a {\em parser}. Input to the parser is a
142stream of {\em tokens}, generated by the {\em lexical analyzer}. This
143chapter describes how the lexical analyzer breaks a file into tokens.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000144
145\section{Line structure}
146
Guido van Rossum7b632a61992-01-16 17:49:21 +0000147A Python program is divided in a number of logical lines. The end of
148a logical line is represented by the token NEWLINE. Statements cannot
149cross logical line boundaries except where NEWLINE is allowed by the
150syntax (e.g., between statements in compound statements).
Guido van Rossumf2612d11991-11-21 13:53:03 +0000151
152\subsection{Comments}
153
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000154A comment starts with a hash character (\verb\#\) that is not part of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000155a string literal, and ends at the end of the physical line. A comment
156always signifies the end of the logical line. Comments are ignored by
157the syntax.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000158
159\subsection{Line joining}
160
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000161Two or more physical lines may be joined into logical lines using
Guido van Rossum7b632a61992-01-16 17:49:21 +0000162backslash characters (\verb/\/), as follows: when a physical line ends
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000163in a backslash that is not part of a string literal or comment, it is
164joined with the following forming a single logical line, deleting the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000165backslash and the following end-of-line character. For example:
166%
167\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000168moth_names = ['Januari', 'Februari', 'Maart', \
169 'April', 'Mei', 'Juni', \
170 'Juli', 'Augustus', 'September', \
171 'Oktober', 'November', 'December']
Guido van Rossum670e5a01992-01-17 14:03:20 +0000172\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000173
174\subsection{Blank lines}
175
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000176A logical line that contains only spaces, tabs, and possibly a
177comment, is ignored (i.e., no NEWLINE token is generated), except that
178during interactive input of statements, an entirely blank logical line
179terminates a multi-line statement.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000180
181\subsection{Indentation}
182
Guido van Rossum7b632a61992-01-16 17:49:21 +0000183Leading whitespace (spaces and tabs) at the beginning of a logical
184line is used to compute the indentation level of the line, which in
185turn is used to determine the grouping of statements.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000186
Guido van Rossum7b632a61992-01-16 17:49:21 +0000187First, tabs are replaced (from left to right) by one to eight spaces
188such that the total number of characters up to there is a multiple of
189eight (this is intended to be the same rule as used by UNIX). The
190total number of spaces preceding the first non-blank character then
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000191determines the line's indentation. Indentation cannot be split over
192multiple physical lines using backslashes.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000193
194The indentation levels of consecutive lines are used to generate
195INDENT and DEDENT tokens, using a stack, as follows.
196
197Before the first line of the file is read, a single zero is pushed on
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000198the stack; this will never be popped off again. The numbers pushed on
199the stack will always be strictly increasing from bottom to top. At
200the beginning of each logical line, the line's indentation level is
201compared to the top of the stack. If it is equal, nothing happens.
202If it larger, it is pushed on the stack, and one INDENT token is
203generated. If it is smaller, it {\em must} be one of the numbers
204occurring on the stack; all numbers on the stack that are larger are
205popped off, and for each number popped off a DEDENT token is
206generated. At the end of the file, a DEDENT token is generated for
207each number remaining on the stack that is larger than zero.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000208
Guido van Rossum7b632a61992-01-16 17:49:21 +0000209Here is an example of a correctly (though confusingly) indented piece
210of Python code:
211
212\begin{verbatim}
213def perm(l):
Guido van Rossum670e5a01992-01-17 14:03:20 +0000214 # Compute the list of all permutations of l
215
Guido van Rossum7b632a61992-01-16 17:49:21 +0000216 if len(l) <= 1:
217 return [l]
218 r = []
219 for i in range(len(l)):
220 s = l[:i] + l[i+1:]
221 p = perm(s)
222 for x in p:
223 r.append(l[i:i+1] + x)
224 return r
225\end{verbatim}
226
227The following example shows various indentation errors:
228
229\begin{verbatim}
230 def perm(l): # error: first line indented
231 for i in range(len(l)): # error: not indented
232 s = l[:i] + l[i+1:]
233 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
234 for x in p:
235 r.append(l[i:i+1] + x)
236 return r # error: inconsistent indent
237\end{verbatim}
238
239(Actually, the first three errors are detected by the parser; only the
240last error is found by the lexical analyzer -- the indentation of
241\verb\return r\ does not match a level popped off the stack.)
242
Guido van Rossumf2612d11991-11-21 13:53:03 +0000243\section{Other tokens}
244
245Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
246exist: identifiers, keywords, literals, operators, and delimiters.
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000247Spaces and tabs are not tokens, but serve to delimit tokens. Where
248ambiguity exists, a token comprises the longest possible string that
249forms a legal token, when read from left to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000250
Guido van Rossumf2612d11991-11-21 13:53:03 +0000251\section{Identifiers}
252
253Identifiers are described by the following regular expressions:
254
255\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000256identifier: (letter|"_") (letter|digit|"_")*
Guido van Rossumf2612d11991-11-21 13:53:03 +0000257letter: lowercase | uppercase
Guido van Rossum743d1e71992-01-07 16:43:53 +0000258lowercase: "a"..."z"
259uppercase: "A"..."Z"
260digit: "0"..."9"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000261\end{verbatim}
262
Guido van Rossum670e5a01992-01-17 14:03:20 +0000263Identifiers are unlimited in length. Case is significant.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000264
Guido van Rossum670e5a01992-01-17 14:03:20 +0000265\subsection{Keywords}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000266
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000267The following identifiers are used as reserved words, or {\em
Guido van Rossum7b632a61992-01-16 17:49:21 +0000268keywords} of the language, and cannot be used as ordinary
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000269identifiers. They must be spelled exactly as written here:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000270
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000271\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000272and del for in print
273break elif from is raise
274class else global not return
275continue except if or try
276def finally import pass while
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000277\end{verbatim}
278
Guido van Rossum743d1e71992-01-07 16:43:53 +0000279% # This Python program sorts and formats the above table
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000280% import string
281% l = []
282% try:
283% while 1:
284% l = l + string.split(raw_input())
285% except EOFError:
286% pass
287% l.sort()
288% for i in range((len(l)+4)/5):
289% for j in range(i, len(l), 5):
290% print string.ljust(l[j], 10),
291% print
Guido van Rossumf2612d11991-11-21 13:53:03 +0000292
293\section{Literals}
294
295\subsection{String literals}
296
297String literals are described by the following regular expressions:
298
299\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000300stringliteral: "'" stringitem* "'"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000301stringitem: stringchar | escapeseq
Guido van Rossum743d1e71992-01-07 16:43:53 +0000302stringchar: <any ASCII character except newline or "\" or "'">
303escapeseq: "'" <any ASCII character except newline>
Guido van Rossumf2612d11991-11-21 13:53:03 +0000304\end{verbatim}
305
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000306String literals cannot span physical line boundaries. Escape
307sequences in strings are actually interpreted according to rules
308simular to those used by Standard C. The recognized escape sequences
309are:
310
311\begin{center}
312\begin{tabular}{|l|l|}
313\hline
314\verb/\\/ & Backslash (\verb/\/) \\
315\verb/\'/ & Single quote (\verb/'/) \\
316\verb/\a/ & ASCII Bell (BEL) \\
317\verb/\b/ & ASCII Backspace (BS) \\
Guido van Rossum7b632a61992-01-16 17:49:21 +0000318%\verb/\E/ & ASCII Escape (ESC) \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000319\verb/\f/ & ASCII Formfeed (FF) \\
320\verb/\n/ & ASCII Linefeed (LF) \\
321\verb/\r/ & ASCII Carriage Return (CR) \\
322\verb/\t/ & ASCII Horizontal Tab (TAB) \\
323\verb/\v/ & ASCII Vertical Tab (VT) \\
324\verb/\/{\em ooo} & ASCII character with octal value {\em ooo} \\
Guido van Rossum743d1e71992-01-07 16:43:53 +0000325\verb/\x/{em xx...} & ASCII character with hex value {\em xx...} \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000326\hline
327\end{tabular}
328\end{center}
329
Guido van Rossum7b632a61992-01-16 17:49:21 +0000330In strict compatibility with in Standard C, up to three octal digits are
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000331accepted, but an unlimited number of hex digits is taken to be part of
332the hex escape (and then the lower 8 bits of the resulting hex number
Guido van Rossum7b632a61992-01-16 17:49:21 +0000333are used in all current implementations...).
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000334
Guido van Rossum7b632a61992-01-16 17:49:21 +0000335All unrecognized escape sequences are left in the string unchanged,
336i.e., {\em the backslash is left in the string.} (This rule is
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000337useful when debugging: if an escape sequence is mistyped, the
Guido van Rossum743d1e71992-01-07 16:43:53 +0000338resulting output is more easily recognized as broken. It also helps a
339great deal for string literals used as regular expressions or
340otherwise passed to other modules that do their own escape handling --
341but you may end up quadrupling backslashes that must appear literally.)
Guido van Rossumf2612d11991-11-21 13:53:03 +0000342
343\subsection{Numeric literals}
344
Guido van Rossum670e5a01992-01-17 14:03:20 +0000345There are three types of numeric literals: plain integers, long
346integers, and floating point numbers.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000347
348Integers and long integers are described by the following regular expressions:
349
350\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000351longinteger: integer ("l"|"L")
Guido van Rossumf2612d11991-11-21 13:53:03 +0000352integer: decimalinteger | octinteger | hexinteger
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000353decimalinteger: nonzerodigit digit* | "0"
354octinteger: "0" octdigit+
355hexinteger: "0" ("x"|"X") hexdigit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000356
Guido van Rossum743d1e71992-01-07 16:43:53 +0000357nonzerodigit: "1"..."9"
358octdigit: "0"..."7"
359hexdigit: digit|"a"..."f"|"A"..."F"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000360\end{verbatim}
361
Guido van Rossum670e5a01992-01-17 14:03:20 +0000362Although both lower case `l'and upper case `L' are allowed as suffix
363for long integers, it is strongly recommended to always use `L', since
364the letter `l' looks too much like the digit `1'.
365
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000366Plain integer decimal literals must be at most $2^{31} - 1$ (i.e., the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000367largest positive integer, assuming 32-bit arithmetic); octal and
368hexadecimal literals may be as large as $2^{32} - 1$. There is no limit
369for long integer literals.
370
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000371Some examples of plain and long integer literals:
Guido van Rossum670e5a01992-01-17 14:03:20 +0000372
373\begin{verbatim}
3747 2147483647 0177 0x80000000
3753L 79228162514264337593543950336L 0377L 0100000000L
376\end{verbatim}
377
Guido van Rossumf2612d11991-11-21 13:53:03 +0000378Floating point numbers are described by the following regular expressions:
379
380\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000381floatnumber: pointfloat | exponentfloat
382pointfloat: [intpart] fraction | intpart "."
383exponentfloat: (intpart | pointfloat) exponent
Guido van Rossumf2612d11991-11-21 13:53:03 +0000384intpart: digit+
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000385fraction: "." digit+
386exponent: ("e"|"E") ["+"|"-"] digit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000387\end{verbatim}
388
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000389The allowed range of floating point literals is
390implementation-dependent.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000391
392Some examples of floating point literals:
Guido van Rossum7b632a61992-01-16 17:49:21 +0000393
394\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00003953.14 10. .001 1e100 3.14e-10
Guido van Rossum7b632a61992-01-16 17:49:21 +0000396\end{verbatim}
397
Guido van Rossum670e5a01992-01-17 14:03:20 +0000398Note that numeric literals do not include a sign; a phrase like
399\verb\-1\ is actually an expression composed of the operator
Guido van Rossum7b632a61992-01-16 17:49:21 +0000400\verb\-\ and the literal \verb\1\.
401
Guido van Rossumf2612d11991-11-21 13:53:03 +0000402\section{Operators}
403
404The following tokens are operators:
405
406\begin{verbatim}
407+ - * / %
408<< >> & | ^ ~
Guido van Rossum743d1e71992-01-07 16:43:53 +0000409< == > <= <> != >=
Guido van Rossumf2612d11991-11-21 13:53:03 +0000410\end{verbatim}
411
Guido van Rossum743d1e71992-01-07 16:43:53 +0000412The comparison operators \verb\<>\ and \verb\!=\ are alternate
413spellings of the same operator.
414
Guido van Rossumf2612d11991-11-21 13:53:03 +0000415\section{Delimiters}
416
Guido van Rossum743d1e71992-01-07 16:43:53 +0000417The following tokens serve as delimiters or otherwise have a special
418meaning:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000419
420\begin{verbatim}
421( ) [ ] { }
Guido van Rossum743d1e71992-01-07 16:43:53 +0000422; , : . ` =
Guido van Rossumf2612d11991-11-21 13:53:03 +0000423\end{verbatim}
424
Guido van Rossum7b632a61992-01-16 17:49:21 +0000425The following printing ASCII characters are not used in Python (except
426in string literals and in comments). Their occurrence is an
427unconditional error:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000428
429\begin{verbatim}
430! @ $ " ?
431\end{verbatim}
432
Guido van Rossum7b632a61992-01-16 17:49:21 +0000433They may be used by future versions of the language though!
434
Guido van Rossumf2612d11991-11-21 13:53:03 +0000435\chapter{Execution model}
436
Guido van Rossum743d1e71992-01-07 16:43:53 +0000437\section{Objects, values and types}
438
439I won't try to define rigorously here what an object is, but I'll give
440some properties of objects that are important to know about.
441
442Every object has an identity, a type and a value. An object's {\em
443identity} never changes once it has been created; think of it as the
444object's (permanent) address. An object's {\em type} determines the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000445operations that an object supports (e.g., does it have a length?) and
446also defines the ``meaning'' of the object's value. The type also
447never changes. The {\em value} of some objects can change; whether
448this is possible is a property of its type.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000449
450Objects are never explicitly destroyed; however, when they become
Guido van Rossum670e5a01992-01-17 14:03:20 +0000451unreachable they may be garbage-collected. An implementation is
452allowed to delay garbage collection or omit it altogether -- it is a
453matter of implementation quality how garbage collection is
454implemented, as long as no objects are collected that are still
455reachable. (Implementation note: the current implementation uses a
Guido van Rossum743d1e71992-01-07 16:43:53 +0000456reference-counting scheme which collects most objects as soon as they
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000457become unreachable, but never collects garbage containing circular
Guido van Rossum743d1e71992-01-07 16:43:53 +0000458references.)
459
Guido van Rossum670e5a01992-01-17 14:03:20 +0000460Note that the use of the implementation's tracing or debugging
461facilities may keep objects alive that would normally be collectable.
462
Guido van Rossum743d1e71992-01-07 16:43:53 +0000463(Some objects contain references to ``external'' resources such as
464open files. It is understood that these resources are freed when the
465object is garbage-collected, but since garbage collection is not
Guido van Rossum670e5a01992-01-17 14:03:20 +0000466guaranteed, such objects also provide an explicit way to release the
467external resource (e.g., a \verb\close\ method). Programs are strongly
Guido van Rossum743d1e71992-01-07 16:43:53 +0000468recommended to use this.)
469
470Some objects contain references to other objects. These references
471are part of the object's value; in most cases, when such a
472``container'' object is compared to another (of the same type), the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000473comparison applies to the {\em values} of the referenced objects (not
474their identities).
Guido van Rossum743d1e71992-01-07 16:43:53 +0000475
Guido van Rossum670e5a01992-01-17 14:03:20 +0000476Types affect almost all aspects of objects.
477Even object identity is affected in some sense: for immutable
Guido van Rossum743d1e71992-01-07 16:43:53 +0000478types, operations that compute new values may actually return a
Guido van Rossum670e5a01992-01-17 14:03:20 +0000479reference to any existing object with the same type and value, while
Guido van Rossum743d1e71992-01-07 16:43:53 +0000480for mutable objects this is not allowed. E.g., after
481
482\begin{verbatim}
483a = 1; b = 1; c = []; d = []
484\end{verbatim}
485
486\verb\a\ and \verb\b\ may or may not refer to the same object, but
487\verb\c\ and \verb\d\ are guaranteed to refer to two different, unique,
488newly created lists.
489
490\section{Execution frames, name spaces, and scopes}
491
Guido van Rossum670e5a01992-01-17 14:03:20 +0000492XXX code blocks, scopes, name spaces, name binding, exceptions
Guido van Rossumf2612d11991-11-21 13:53:03 +0000493
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000494\chapter{The standard type hierarchy}
495
496The following types are built into Python. Extension modules
497written in C can define additional types. Future versions of Python
498may also add types to the type hierarchy (e.g., rational or complex
499numbers, lists of efficiently stored integers, etc.).
500
501\begin{description}
502
503\item[None]
504This type has a single value. There is a single object with this value.
505This object is accessed through the built-in name \verb\None\.
506It is returned from functions that don't explicitly return an object.
507
508\item[Numbers]
509These are created by numeric literals and returned as results
510by arithmetic operators and arithmetic built-in functions.
511Numeric objects are immutable; once created their value never changes.
512Python numbers are of course strongly related to mathematical numbers,
513but subject to the limitations of numerical representation in computers.
514
515Python distinguishes between integers and floating point numbers:
516
517\begin{description}
518\item[Integers]
519These represent elements from the mathematical set of whole numbers.
520
521There are two types of integers:
522
523\begin{description}
524
525\item[Plain integers]
526These represent numbers in the range $-2^{31}$ through $2^{31}-1$.
527(The range may be larger on machines with a larger natural word
528size, but not smaller.)
529When the result of an operation falls outside this range, the
530exception \verb\OverflowError\ is raised.
531For the purpose of shift and mask operations, integers are assumed to
532have a binary, 2's complement notation using 32 or more bits, and
533hiding no bits from the user (i.e., all $2^{32}$ different bit
534patterns correspond to different values).
535
536\item[Long integers]
537These represent numbers in an unlimited range, subject to avaiable
538(virtual) memory only. For the purpose of shift and mask operations,
539a binary representation is assumed, and negative numbers are
540represented in a variant of 2's complement which gives the illusion of
541an infinite string of sign bits extending to the left.
542
543\end{description} % Integers
544
545The rules for integer representation are intended to give the most
546meaningful interpretation of shift and mask operations involving
547negative integers and the least surprises when switching between the
548plain and long integer domains. For any operation except left shift,
549if it yields a result in the plain integer domain without causing
550overflow, it will yield the same result in the long integer domain or
551when using mixed operands.
552
553\item[Floating point numbers]
554These represent machine-level double precision floating point numbers.
555You are at the mercy of the underlying machine architecture and
556C implementation for the accepted range and handling of overflow.
557
558\end{description} % Numbers
559
560\item[Sequences]
561These represent finite ordered sets indexed by natural numbers.
562The built-in function \verb\len()\ returns the number of elements
563of a sequence. When this number is $n$, the index set contains
564the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence
565\verb\a\ is selected by \verb\a[i]\.
566
567Sequences also support slicing: \verb\a[i:j]\ selects all elements
568with index $k$ such that $i < k < j$. When used as an expression,
569a slice is a sequence of the same type -- this implies that the
570index set is renumbered so that it starts at 0 again.
571
572Sequences are distinguished according to their mutability:
573
574\begin{description}
575%
576\item[Immutable sequences]
577An object of an immutable sequence type cannot change once it is
578created. (If the object contains references to other objects,
579these other objects may be mutable and may be changed; however
580the collection of objects directly referenced by an immutable object
581cannot change.)
582
583The following types are immutable sequences:
584
585\begin{description}
586
587\item[Strings]
588The elements of a string are characters. There is no separate
589character type; a character is represented by a string of one element.
590Characters represent (at least) 8-bit bytes. The built-in
591functions \verb\chr()\ and \verb\ord()\ convert between characters
592and nonnegative integers representing the byte values.
593Bytes with the values 0-127 represent the corresponding ASCII values.
594
595(On systems whose native character set is not ASCII, strings may use
596EBCDIC in their internal representation, provided the functions
597\verb\chr()\ and \verb\ord()\ implement a mapping between ASCII and
598EBCDIC, and string comparisons preserve the ASCII order.
599Or perhaps someone can propose a better rule?)
600
601\item[Tuples]
602The elements of a tuple are arbitrary Python objects.
603Tuples of two or more elements are formed by comma-separated lists
604of expressions. A tuple of one element can be formed by affixing
605a comma to an expression (an expression by itself of course does
606not create a tuple). An empty tuple can be formed by enclosing
607`nothing' in parentheses.
608
609\end{description} % Immutable sequences
610
611\item[Mutable sequences]
612Mutable sequences can be changed after they are created.
613The subscript and slice notations can be used as the target
614of assignment and \verb\del\ (delete) statements.
615
616There is currently a single mutable sequence type:
617
618\begin{description}
619
620\item[Lists]
621The elements of a list are arbitrary Python objects.
622Lists are formed by placing a comma-separated list of expressions
623in square brackets. (Note that there are no special cases for lists
624of length 0 or 1.)
625
626\end{description} % Mutable sequences
627
628\end{description} % Sequences
629
630\item[Mapping types]
631These represent finite sets of objects indexed by arbitrary index sets.
632The subscript notation \verb\a[k]\ selects the element indexed
633by \verb\k\ from the mapping \verb\a\; this can be used in
634expressions and as the target of assignments or \verb\del\ statements.
635The built-in function \verb\len()\ returns the number of elements
636in a mapping.
637
638There is currently a single mapping type:
639
640\begin{description}
641
642\item[Dictionaries]
643These represent finite sets of objects indexed by strings.
644Dictionaries are created by the \verb\{...}\ notation (see section
645\ref{dict}). (Implementation note: the strings used for indexing must
646not contain null bytes.)
647
648\end{description} % Mapping types
649
650\item[Callable types]
651These are the types to which the function call operation can be applied:
652
653\begin{description}
654\item[User-defined functions]
655XXX
656\item[Built-in functions]
657XXX
658\item[User-defined methods]
659XXX
660\item[Built-in methods]
661XXX
662\item[User-defined classes]
663XXX
664\end{description}
665
666\item[Modules]
667XXX
668
669\item[Class instances]
670XXX
671
672\item[Files]
673XXX
674
675\item[Internal types]
676A few types used internally by the interpreter are exposed to the user.
677Their definition may change with future versions of the interpreter,
678but they are mentioned here for completeness.
679
680\begin{description}
681\item[Code objects]
682XXX
683\item[Traceback objects]
684XXX
685\end{description} % Internal types
686
687\end{description} % Types
688
Guido van Rossumf2612d11991-11-21 13:53:03 +0000689\chapter{Expressions and conditions}
690
Guido van Rossum743d1e71992-01-07 16:43:53 +0000691From now on, extended BNF notation will be used to describe syntax,
692not lexical analysis.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000693
694This chapter explains the meaning of the elements of expressions and
695conditions. Conditions are a superset of expressions, and a condition
Guido van Rossum670e5a01992-01-17 14:03:20 +0000696may be used wherever an expression is required by enclosing it in
697parentheses. The only places where expressions are used in the syntax
698instead of conditions is in expression statements and on the
699right-hand side of assignments; this catches some nasty bugs like
700accedentally writing \verb\x == 1\ instead of \verb\x = 1\.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000701
Guido van Rossum670e5a01992-01-17 14:03:20 +0000702The comma has several roles in Python's syntax. It is usually an
Guido van Rossum743d1e71992-01-07 16:43:53 +0000703operator with a lower precedence than all others, but occasionally
Guido van Rossum670e5a01992-01-17 14:03:20 +0000704serves other purposes as well; e.g., it separates function arguments,
705is used in list and dictionary constructors, and has special semantics
706in \verb\print\ statements.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000707
708When (one alternative of) a syntax rule has the form
709
710\begin{verbatim}
711name: othername
712\end{verbatim}
713
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000714and no semantics are given, the semantics of this form of \verb\name\
715are the same as for \verb\othername\.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000716
717\section{Arithmetic conversions}
718
719When a description of an arithmetic operator below uses the phrase
720``the numeric arguments are converted to a common type'',
721this both means that if either argument is not a number, a
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000722\verb\TypeError\ exception is raised, and that otherwise
Guido van Rossumf2612d11991-11-21 13:53:03 +0000723the following conversions are applied:
724
725\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000726\item first, if either argument is a floating point number,
Guido van Rossumf2612d11991-11-21 13:53:03 +0000727 the other is converted to floating point;
728\item else, if either argument is a long integer,
729 the other is converted to long integer;
Guido van Rossum670e5a01992-01-17 14:03:20 +0000730\item otherwise, both must be plain integers and no conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +0000731 is necessary.
732\end{itemize}
733
Guido van Rossumf2612d11991-11-21 13:53:03 +0000734\section{Atoms}
735
Guido van Rossum670e5a01992-01-17 14:03:20 +0000736Atoms are the most basic elements of expressions. Forms enclosed in
737reverse quotes or in parentheses, brackets or braces are also
738categorized syntactically as atoms. The syntax for atoms is:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000739
740\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000741atom: identifier | literal | enclosure
742enclosure: parenth_form | list_display | dict_display | string_conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +0000743\end{verbatim}
744
745\subsection{Identifiers (Names)}
746
747An identifier occurring as an atom is a reference to a local, global
Guido van Rossum670e5a01992-01-17 14:03:20 +0000748or built-in name binding. If a name can be assigned to anywhere in a
749code block, and is not mentioned in a \verb\global\ statement in that
750code block, it refers to a local name throughout that code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000751Otherwise, it refers to a global name if one exists, else to a
752built-in name.
753
Guido van Rossum670e5a01992-01-17 14:03:20 +0000754When the name is bound to an object, evaluation of the atom yields
755that object. When a name is not bound, an attempt to evaluate it
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000756raises a \verb\NameError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000757
758\subsection{Literals}
759
Guido van Rossum670e5a01992-01-17 14:03:20 +0000760Python knows string and numeric literals:
761
762\begin{verbatim}
763literal: stringliteral | integer | longinteger | floatnumber
764\end{verbatim}
765
Guido van Rossumf2612d11991-11-21 13:53:03 +0000766Evaluation of a literal yields an object of the given type
767(string, integer, long integer, floating point number)
768with the given value.
769The value may be approximated in the case of floating point literals.
770
Guido van Rossum670e5a01992-01-17 14:03:20 +0000771All literals correspond to immutable data types, and hence the
772object's identity is less important than its value. Multiple
773evaluations of literals with the same value (either the same
774occurrence in the program text or a different occurrence) may obtain
775the same object or a different object with the same value.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000776
777(In the original implementation, all literals in the same code block
778with the same type and value yield the same object.)
779
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000780\subsection{Parenthesized forms}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000781
Guido van Rossum670e5a01992-01-17 14:03:20 +0000782A parenthesized form is an optional condition list enclosed in
783parentheses:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000784
Guido van Rossum670e5a01992-01-17 14:03:20 +0000785\begin{verbatim}
786parenth_form: "(" [condition_list] ")"
787\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000788
Guido van Rossum670e5a01992-01-17 14:03:20 +0000789A parenthesized condition list yields whatever that condition list
790yields.
791
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000792An empty pair of parentheses yields an empty tuple object. Since
793tuples are immutable, the rules for literals apply here.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000794
795(Note that tuples are not formed by the parentheses, but rather by use
796of the comma operator. The exception is the empty tuple, for which
797parentheses {\em are} required -- allowing unparenthesized ``nothing''
798in expressions would causes ambiguities and allow common typos to
799pass uncaught.)
Guido van Rossumf2612d11991-11-21 13:53:03 +0000800
801\subsection{List displays}
802
Guido van Rossum670e5a01992-01-17 14:03:20 +0000803A list display is a possibly empty series of conditions enclosed in
804square brackets:
805
806\begin{verbatim}
807list_display: "[" [condition_list] "]"
808\end{verbatim}
809
Guido van Rossumf2612d11991-11-21 13:53:03 +0000810A list display yields a new list object.
811
812If it has no condition list, the list object has no items.
813Otherwise, the elements of the condition list are evaluated
814from left to right and inserted in the list object in that order.
815
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000816\subsection{Dictionary displays} \label{dict}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000817
Guido van Rossum670e5a01992-01-17 14:03:20 +0000818A dictionary display is a possibly empty series of key/datum pairs
819enclosed in curly braces:
820
821\begin{verbatim}
822dict_display: "{" [key_datum_list] "}"
823key_datum_list: [key_datum ("," key_datum)* [","]
824key_datum: condition ":" condition
825\end{verbatim}
826
Guido van Rossumf2612d11991-11-21 13:53:03 +0000827A dictionary display yields a new dictionary object.
828
Guido van Rossum670e5a01992-01-17 14:03:20 +0000829The key/datum pairs are evaluated from left to right to define the
830entries of the dictionary: each key object is used as a key into the
831dictionary to store the corresponding datum.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000832
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000833Keys must be strings, otherwise a \verb\TypeError\ exception is raised.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000834Clashes between duplicate keys are not detected; the last datum
835(textually rightmost in the display) stored for a given key value
836prevails.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000837
838\subsection{String conversions}
839
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000840A string conversion is a condition list enclosed in reverse (or
Guido van Rossum670e5a01992-01-17 14:03:20 +0000841backward) quotes:
842
843\begin{verbatim}
844string_conversion: "`" condition_list "`"
845\end{verbatim}
846
Guido van Rossumf2612d11991-11-21 13:53:03 +0000847A string conversion evaluates the contained condition list and converts the
848resulting object into a string according to rules specific to its type.
849
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000850If the object is a string, a number, \verb\None\, or a tuple, list or
Guido van Rossum670e5a01992-01-17 14:03:20 +0000851dictionary containing only objects whose type is one of these, the
852resulting string is a valid Python expression which can be passed to
853the built-in function \verb\eval()\ to yield an expression with the
Guido van Rossumf2612d11991-11-21 13:53:03 +0000854same value (or an approximation, if floating point numbers are
855involved).
856
857(In particular, converting a string adds quotes around it and converts
858``funny'' characters to escape sequences that are safe to print.)
859
Guido van Rossum670e5a01992-01-17 14:03:20 +0000860It is illegal to attempt to convert recursive objects (e.g., lists or
861dictionaries that contain a reference to themselves, directly or
862indirectly.)
Guido van Rossumf2612d11991-11-21 13:53:03 +0000863
864\section{Primaries}
865
866Primaries represent the most tightly bound operations of the language.
867Their syntax is:
868
869\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000870primary: atom | attributeref | subscription | slicing | call
Guido van Rossumf2612d11991-11-21 13:53:03 +0000871\end{verbatim}
872
873\subsection{Attribute references}
874
Guido van Rossum670e5a01992-01-17 14:03:20 +0000875An attribute reference is a primary followed by a period and a name:
876
877\begin{verbatim}
878attributeref: primary "." identifier
879\end{verbatim}
880
881The primary must evaluate to an object of a type that supports
882attribute references, e.g., a module or a list. This object is then
883asked to produce the attribute whose name is the identifier. If this
884attribute is not available, the exception \verb\AttributeError\ is
885raised. Otherwise, the type and value of the object produced is
886determined by the object. Multiple evaluations of the same attribute
887reference may yield different objects.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000888
889\subsection{Subscriptions}
890
Guido van Rossum670e5a01992-01-17 14:03:20 +0000891A subscription selects an item of a sequence or mapping object:
892
893\begin{verbatim}
894subscription: primary "[" condition "]"
895\end{verbatim}
896
897The primary must evaluate to an object of a sequence or mapping type.
898
899If it is a mapping, the condition must evaluate to an object whose
900value is one of the keys of the mapping, and the subscription selects
901the value in the mapping that corresponds to that key.
902
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000903If it is a sequence, the condition must evaluate to a plain integer.
904If this value is negative, the length of the sequence is added to it
905(so that, e.g., \verb\x[-1]\ selects the last item of \verb\x\.)
906The resulting value must be a nonnegative integer smaller than the
907number of items in the sequence, and the subscription selects the item
908whose index is that value (counting from zero).
Guido van Rossum670e5a01992-01-17 14:03:20 +0000909
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000910A string's items are characters. A character is not a separate data
Guido van Rossum670e5a01992-01-17 14:03:20 +0000911type but a string of exactly one character.
912
Guido van Rossumf2612d11991-11-21 13:53:03 +0000913\subsection{Slicings}
914
Guido van Rossum670e5a01992-01-17 14:03:20 +0000915A slicing selects a range of items in a sequence object:
916
917\begin{verbatim}
918slicing: primary "[" [condition] ":" [condition] "]"
919\end{verbatim}
920
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000921The primary must evaluate to a sequence object. The lower and upper
922bound expressions, if present, must evaluate to plain integers;
923defaults are zero and the sequence's length, respectively. If either
924bound is negative, the sequence's length is added to it. The slicing
925now selects all items with index $k$ such that $i <= k < j$ where $i$
926and $j$ are the specified lower and upper bounds. This may be an
927empty sequence. It is not an error if $i$ or $j$ lie outside the
928range of valid indexes (such items don't exist so they aren't
929selected).
Guido van Rossum670e5a01992-01-17 14:03:20 +0000930
931\subsection{Calls}
932
933A call calls a function with a possibly empty series of arguments:
934
935\begin{verbatim}
936call: primary "(" [condition_list] ")"
937\end{verbatim}
938
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000939The primary must evaluate to a callable object (user-defined
940functions, built-in functions, methods of built-in objects, class
941objects, and methods of class instances are callable). If it is a
942class, the argument list must be empty.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000943
944XXX explain what happens on function call
945
Guido van Rossumf2612d11991-11-21 13:53:03 +0000946\section{Factors}
947
948Factors represent the unary numeric operators.
949Their syntax is:
950
951\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000952factor: primary | "-" factor | "+" factor | "~" factor
Guido van Rossumf2612d11991-11-21 13:53:03 +0000953\end{verbatim}
954
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000955The unary \verb\"-"\ operator yields the negative of its
956numeric argument.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000957
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000958The unary \verb\"+"\ operator yields its numeric argument unchanged.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000959
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000960The unary \verb\"~"\ operator yields the bit-wise negation of its
961plain or long integer argument. The bit-wise negation negation of
962\verb\x\ is defined as \verb\-(x+1)\.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000963
964In all three cases, if the argument does not have the proper type,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000965a \verb\TypeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000966
967\section{Terms}
968
969Terms represent the most tightly binding binary operators:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000970%
Guido van Rossumf2612d11991-11-21 13:53:03 +0000971\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000972term: factor | term "*" factor | term "/" factor | term "%" factor
Guido van Rossumf2612d11991-11-21 13:53:03 +0000973\end{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000974%
975The \verb\"*"\ (multiplication) operator yields the product of its
Guido van Rossum670e5a01992-01-17 14:03:20 +0000976arguments. The arguments must either both be numbers, or one argument
977must be a plain integer and the other must be a sequence. In the
978former case, the numbers are converted to a common type and then
979multiplied together. In the latter case, sequence repetition is
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000980performed; a negative repetition factor yields an empty sequence.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000981
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000982The \verb\"/"\ (division) operator yields the quotient of its
Guido van Rossum670e5a01992-01-17 14:03:20 +0000983arguments. The numeric arguments are first converted to a common
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000984type. Plain or long integer division yields an integer of the same
985type; the result is that of mathematical division with the `floor'
986function applied to the result. Division by zero raises the
987\verb\ZeroDivisionError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000988
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000989The \verb\"%"\ (modulo) operator yields the remainder from the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000990division of the first argument by the second. The numeric arguments
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000991are first converted to a common type. A zero right argument raises the
992\verb\ZeroDivisionError\ exception. The arguments may be floating point
993numbers, e.g., \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo operator
Guido van Rossum670e5a01992-01-17 14:03:20 +0000994always yields a result with the same sign as its second operand (or
995zero); the absolute value of the result is strictly smaller than the
996second operand.
997
998The integer division and modulo operators are connected by the
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000999following identity: \verb\x == (x/y)*y + (x%y)\.
1000Integer division and modulo are also connected with the built-in
1001function \verb\divmod()\: \verb\divmod(x, y) == (x/y, x%y)\.
1002These identities don't hold for floating point numbers; there a
1003similar identity holds where \verb\x/y\ is replaced by
1004\verb\floor(x/y)\).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001005
1006\section{Arithmetic expressions}
1007
1008\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001009arith_expr: term | arith_expr "+" term | arith_expr "-" term
Guido van Rossumf2612d11991-11-21 13:53:03 +00001010\end{verbatim}
1011
Guido van Rossum670e5a01992-01-17 14:03:20 +00001012The \verb|"+"| operator yields the sum of its arguments. The
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001013arguments must either both be numbers, or both sequences of the same
1014type. In the former case, the numbers are converted to a common type
1015and then added together. In the latter case, the sequences are
1016concatenated.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001017
Guido van Rossum743d1e71992-01-07 16:43:53 +00001018The \verb|"-"| operator yields the difference of its arguments.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001019The numeric arguments are first converted to a common type.
1020
1021\section{Shift expressions}
1022
1023\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001024shift_expr: arith_expr | shift_expr ( "<<" | ">>" ) arith_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001025\end{verbatim}
1026
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001027These operators accept plain or long integers as arguments. The
1028arguments are converted to a common type. They shift the first
1029argument to the left or right by the number of bits given by the
1030second argument.
1031
1032A right shift by $n$ bits is defined as division by $2^n$. A left
1033shift by $n$ bits is defined as multiplication with $2^n$ without
1034overflow check; for plain integers this drops bits if the result is
1035not less than $2^{31} - 1$ in absolute value.
1036
1037Negative shift counts raise a \verb\ValueError\ exception.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001038
1039\section{Bitwise AND expressions}
1040
1041\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001042and_expr: shift_expr | and_expr "&" shift_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001043\end{verbatim}
1044
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001045This operator yields the bitwise AND of its arguments, which must be
1046plain or long integers. The arguments are converted to a common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001047
1048\section{Bitwise XOR expressions}
1049
1050\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001051xor_expr: and_expr | xor_expr "^" and_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001052\end{verbatim}
1053
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001054This operator yields the bitwise exclusive OR of its arguments, which
1055must be plain or long integers. The arguments are converted to a
1056common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001057
1058\section{Bitwise OR expressions}
1059
1060\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001061or_expr: xor_expr | or_expr "|" xor_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001062\end{verbatim}
1063
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001064This operator yields the bitwise OR of its arguments, which must be
1065plain or long integers. The arguments are converted to a common type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001066
1067\section{Comparisons}
1068
1069\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001070comparison: or_expr (comp_operator or_expr)*
Guido van Rossum743d1e71992-01-07 16:43:53 +00001071comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001072\end{verbatim}
1073
1074Comparisons yield integer value: 1 for true, 0 for false.
1075
1076Comparisons can be chained arbitrarily,
1077e.g., $x < y <= z$ is equivalent to
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001078$x < y$ \verb\and\ $y <= z$, except that $y$ is evaluated only once
Guido van Rossumf2612d11991-11-21 13:53:03 +00001079(but in both cases $z$ is not evaluated at all when $x < y$ is
1080found to be false).
1081
1082Formally, $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 +00001083$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 +00001084$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
1085
1086Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
1087between $e_0$ and $e_2$, e.g., $x < y > z$ is perfectly legal.
1088
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001089The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with
1090C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below
1091\verb\<>\ is also implied.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001092
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001093The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
Guido van Rossumf2612d11991-11-21 13:53:03 +00001094the values of two objects. The objects needn't have the same type.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001095If both are numbers, they are coverted to a common type. Otherwise,
1096objects of different types {\em always} compare unequal, and are
1097ordered consistently but arbitrarily.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001098
1099(This unusual
1100definition of comparison is done to simplify the definition of
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001101operations like sorting and the \verb\in\ and \verb\not in\ operators.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001102
1103Comparison of objects of the same type depends on the type:
1104
1105\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001106
1107\item
1108Numbers are compared arithmetically.
1109
1110\item
1111Strings are compared lexicographically using the numeric equivalents
1112(the result of the built-in function \verb\ord\) of their characters.
1113
1114\item
1115Tuples and lists are compared lexicographically using comparison of
1116corresponding items.
1117
1118\item
1119Mappings (dictionaries) are compared through lexicographic
1120comparison of their sorted (key, value) lists.%
1121\footnote{This is expensive since it requires sorting the keys first,
1122but about the only sensible definition. It was tried to compare
1123dictionaries using the following rules, but this gave surprises in
1124cases like \verb|if d == {}: ...|.}
1125
1126\item
1127Most other types compare unequal unless they are the same object;
1128the choice whether one object is considered smaller or larger than
1129another one is made arbitrarily but consistently within one
1130execution of a program.
1131
Guido van Rossumf2612d11991-11-21 13:53:03 +00001132\end{itemize}
1133
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001134The operators \verb\in\ and \verb\not in\ test for sequence
1135membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and
1136only if there exists an index $i$ such that $x = y[i]$.
1137$x ~\verb\not in\~ y$ yields the inverse truth value. The exception
1138\verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is
1139a string and $x$ is not a string of length one.%
1140\footnote{The latter restriction is sometimes a nuisance.}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001141
1142The operators \verb\is\ and \verb\is not\ compare object identity:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001143$x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same
1144object. $x ~\verb\is not\~ y$ yields the inverse truth value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001145
1146\section{Boolean operators}
1147
1148\begin{verbatim}
1149condition: or_test
Guido van Rossum743d1e71992-01-07 16:43:53 +00001150or_test: and_test | or_test "or" and_test
1151and_test: not_test | and_test "and" not_test
1152not_test: comparison | "not" not_test
Guido van Rossumf2612d11991-11-21 13:53:03 +00001153\end{verbatim}
1154
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001155In the context of Boolean operators, and also when conditions are used
1156by control flow statements, the following values are interpreted as
1157false: \verb\None\, numeric zero of all types, empty sequences
1158(strings, tuples and lists), and empty mappings (dictionaries). All
1159other values are interpreted as true.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001160
1161The operator \verb\not\ yields 1 if its argument is false, 0 otherwise.
1162
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001163The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001164$x$ is returned; otherwise, $y$ is evaluated and returned.
1165
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001166The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001167$x$ is returned; otherwise, $y$ is evaluated and returned.
1168
1169(Note that \verb\and\ and \verb\or\ do not restrict the value and type
1170they return to 0 and 1, but rather return the last evaluated argument.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001171This is sometimes useful, e.g., if \verb\s\ is a string, which should be
1172replaced by a default value if it is empty, \verb\s or 'foo'\
Guido van Rossumf2612d11991-11-21 13:53:03 +00001173returns the desired value. Because \verb\not\ has to invent a value
1174anyway, it does not bother to return a value of the same type as its
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001175argument, so \verb\not 'foo'\ yields \verb\0\, not \verb\''\.)
1176
1177\section{Expression lists and condition lists}
1178
1179\begin{verbatim}
1180expr_list: or_expr ("," or_expr)* [","]
1181cond_list: condition ("," condition)* [","]
1182\end{verbatim}
1183
1184The only difference between expression lists and condition lists is
1185the lowest priority of operators that can be used in them without
1186being enclosed in parentheses; condition lists allow all operators,
1187while expression lists don't allow comparisons and Boolean operators
1188(they do allow bitwise and shift operators though).
1189
1190Expression lists are used in expression statements and assignments;
1191condition lists are used everywhere else.
1192
1193An expression (condition) list containing at least one comma yields a
1194tuple. The length of the tuple is the number of expressions
1195(conditions) in the list. The expressions (conditions) are evaluated
1196from left to right.
1197
1198The trailing comma is required only to create a single tuple (a.k.a. a
1199{\em singleton}); it is optional in all other cases. A single
1200expression (condition) without a trailing comma doesn't create a
1201tuple, but rather yields the value of that expression (condition).
1202
1203To create an empty tuple, use an empty pair of parentheses: \verb\()\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001204
1205\chapter{Simple statements}
1206
1207Simple statements are comprised within a single logical line.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001208Several simple statements may occur on a single line separated
Guido van Rossumf2612d11991-11-21 13:53:03 +00001209by semicolons. The syntax for simple statements is:
1210
1211\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001212stmt_list: simple_stmt (";" simple_stmt)* [";"]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001213simple_stmt: expression_stmt
1214 | assignment
1215 | pass_stmt
1216 | del_stmt
1217 | print_stmt
1218 | return_stmt
1219 | raise_stmt
1220 | break_stmt
1221 | continue_stmt
1222 | import_stmt
Guido van Rossum743d1e71992-01-07 16:43:53 +00001223 | global_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001224\end{verbatim}
1225
1226\section{Expression statements}
1227
1228\begin{verbatim}
1229expression_stmt: expression_list
1230\end{verbatim}
1231
1232An expression statement evaluates the expression list (which may
1233be a single expression).
1234If the value is not \verb\None\, it is converted to a string
1235using the rules for string conversions, and the resulting string
1236is written to standard output on a line by itself.
1237
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001238(The exception for \verb\None\ is made so that procedure calls, which
1239are syntactically equivalent to expressions, do not cause any output.
1240A tuple with only \verb\None\ items is written normally.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001241
1242\section{Assignments}
1243
1244\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001245assignment: (target_list "=")+ expression_list
Guido van Rossum743d1e71992-01-07 16:43:53 +00001246target_list: target ("," target)* [","]
1247target: identifier | "(" target_list ")" | "[" target_list "]"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001248 | attributeref | subscription | slicing
1249\end{verbatim}
1250
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001251(See the section on primaries for the syntax definition of the last
Guido van Rossumf2612d11991-11-21 13:53:03 +00001252three symbols.)
1253
1254An assignment evaluates the expression list (remember that this can
1255be a single expression or a comma-separated list,
1256the latter yielding a tuple)
1257and assigns the single resulting object to each of the target lists,
1258from left to right.
1259
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001260Assignment is defined recursively depending on the form of the target.
1261When a target is part of a mutable object (an attribute reference,
1262subscription or slicing), the mutable object must ultimately perform
1263the assignment and decide about its validity, and may raise an
1264exception if the assignment is unacceptable. The rules observed by
1265various types and the exceptions raised are given with the definition
1266of the object types (some of which are defined in the library
1267reference).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001268
1269Assignment of an object to a target list is recursively
1270defined as follows.
1271
1272\begin{itemize}
1273\item
1274If the target list contains no commas (except in nested constructs):
1275the object is assigned to the single target contained in the list.
1276
1277\item
1278If the target list contains commas (that are not in nested constructs):
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001279the object must be a tuple with the same number of items
Guido van Rossumf2612d11991-11-21 13:53:03 +00001280as the list contains targets, and the items are assigned, from left
1281to right, to the corresponding targets.
1282
1283\end{itemize}
1284
1285Assignment of an object to a (non-list)
1286target is recursively defined as follows.
1287
1288\begin{itemize}
1289
1290\item
1291If the target is an identifier (name):
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001292\begin{itemize}
1293\item
1294If the name does not occur in a \verb\global\ statement in the current
1295code block: the object is bound to that name in the current local
1296name space.
1297\item
1298Otherwise: the object is bound to that name in the current global name
1299space.
1300\end{itemize}
1301A previous binding of the same name in the same name space is undone.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001302
1303\item
1304If the target is a target list enclosed in parentheses:
1305the object is assigned to that target list.
1306
1307\item
1308If the target is a target list enclosed in square brackets:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001309the object must be a list with the same number of items
Guido van Rossumf2612d11991-11-21 13:53:03 +00001310as the target list contains targets,
1311and the list's items are assigned, from left to right,
1312to the corresponding targets.
1313
1314\item
1315If the target is an attribute reference:
1316The primary expression in the reference is evaluated.
1317It should yield an object with assignable attributes;
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001318if this is not the case, \verb\TypeError\ is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001319That object is then asked to assign the assigned object
1320to the given attribute; if it cannot perform the assignment,
1321it raises an exception.
1322
1323\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001324If the target is a subscription: The primary expression in the
1325reference is evaluated. It should yield either a mutable sequence
1326(list) object or a mapping (dictionary) object. Next, the subscript
1327expression is evaluated.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001328
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001329If the primary is a sequence object, the subscript must yield a plain
1330integer. If it is negative, the sequence's length is added to it.
1331The resulting value must be a nonnegative integer less than the
1332sequence's length, and the sequence is asked to assign the assigned
1333object to its item with that index. If the index is out of range,
1334\verb\IndexError\ is raised (assignment to a subscripted sequence
1335cannot add new items to a list).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001336
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001337If the primary is a mapping object, the subscript must have a type
1338compatible with the mapping's key type, and the mapping is then asked
1339to to create a key/datum pair which maps the subscript to the assigned
1340object. This can either replace an existing key/value pair with the
1341same key value, or insert a new key/value pair (if no key with the
1342same value existed).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001343
1344\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001345If the target is a slicing: The primary expression in the reference is
1346evaluated. It should yield a mutable sequence (list) object. The
1347assigned object should be a sequence object of the same type. Next,
1348the lower and upper bound expressions are evaluated, insofar they are
1349present; defaults are zero and the sequence's length. The bounds
1350should evaluate to (small) integers. If either bound is negative, the
1351sequence's length is added to it. The resulting bounds are clipped to
1352lie between zero and the sequence's length, inclusive. Finally, the
1353sequence object is asked to replace the items indicated by the slice
1354with the items of the assigned sequence. This may change the
1355sequence's length, if it allows it.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001356
1357\end{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001358
Guido van Rossumf2612d11991-11-21 13:53:03 +00001359(In the original implementation, the syntax for targets is taken
1360to be the same as for expressions, and invalid syntax is rejected
1361during the code generation phase, causing less detailed error
1362messages.)
1363
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001364\section{The \verb\pass\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001365
1366\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001367pass_stmt: "pass"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001368\end{verbatim}
1369
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001370\verb\pass\ is a null operation -- when it is executed, nothing
1371happens. It is useful as a placeholder when a statement is
1372required syntactically, but no code needs to be executed, for example:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001373
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001374\begin{verbatim}
1375def f(arg): pass # a no-op function
1376
1377class C: pass # an empty class
1378\end{verbatim}
1379
1380\section{The \verb\del\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001381
1382\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001383del_stmt: "del" target_list
Guido van Rossumf2612d11991-11-21 13:53:03 +00001384\end{verbatim}
1385
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001386Deletion is recursively defined very similar to the way assignment is
1387defined. Rather that spelling it out in full details, here are some
1388hints.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001389
1390Deletion of a target list recursively deletes each target,
1391from left to right.
1392
1393Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001394from the local or global name space, depending on whether the name
1395occurs in a \verb\global\ statement in the same code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001396
1397Deletion of attribute references, subscriptions and slicings
1398is passed to the primary object involved; deletion of a slicing
1399is in general equivalent to assignment of an empty slice of the
1400right type (but even this is determined by the sliced object).
1401
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001402\section{The \verb\print\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001403
1404\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001405print_stmt: "print" [ condition ("," condition)* [","] ]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001406\end{verbatim}
1407
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001408\verb\print\ evaluates each condition in turn and writes the resulting
1409object to standard output (see below). If an object is not a string,
1410it is first converted to a string using the rules for string
1411conversions. The (resulting or original) string is then written. A
1412space is written before each object is (converted and) written, unless
1413the output system believes it is positioned at the beginning of a
1414line. This is the case: (1) when no characters have yet been written
1415to standard output; or (2) when the last character written to standard
1416output is \verb/\n/; or (3) when the last write operation on standard
1417output was not a \verb\print\ statement. (In some cases it may be
1418functional to write an empty string to standard output for this
1419reason.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001420
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001421A \verb/"\n"/ character is written at the end, unless the \verb\print\
1422statement ends with a comma. This is the only action if the statement
1423contains just the keyword \verb\print\.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001424
1425Standard output is defined as the file object named \verb\stdout\
1426in the built-in module \verb\sys\. If no such object exists,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001427or if it is not a writable file, a \verb\RuntimeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001428(The original implementation attempts to write to the system's original
1429standard output instead, but this is not safe, and should be fixed.)
1430
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001431\section{The \verb\return\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001432
1433\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001434return_stmt: "return" [condition_list]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001435\end{verbatim}
1436
1437\verb\return\ may only occur syntactically nested in a function
1438definition, not within a nested class definition.
1439
1440If a condition list is present, it is evaluated, else \verb\None\
1441is substituted.
1442
1443\verb\return\ leaves the current function call with the condition
1444list (or \verb\None\) as return value.
1445
1446When \verb\return\ passes control out of a \verb\try\ statement
1447with a \verb\finally\ clause, that finally clause is executed
1448before really leaving the function.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001449
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001450\section{The \verb\raise\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001451
1452\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001453raise_stmt: "raise" condition ["," condition]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001454\end{verbatim}
1455
1456\verb\raise\ evaluates its first condition, which must yield
1457a string object. If there is a second condition, this is evaluated,
1458else \verb\None\ is substituted.
1459
1460It then raises the exception identified by the first object,
1461with the second one (or \verb\None\) as its parameter.
1462
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001463\section{The \verb\break\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001464
1465\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001466break_stmt: "break"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001467\end{verbatim}
1468
1469\verb\break\ may only occur syntactically nested in a \verb\for\
1470or \verb\while\ loop, not nested in a function or class definition.
1471
1472It terminates the neares enclosing loop, skipping the optional
1473\verb\else\ clause if the loop has one.
1474
1475If a \verb\for\ loop is terminated by \verb\break\, the loop control
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001476target keeps its current value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001477
1478When \verb\break\ passes control out of a \verb\try\ statement
1479with a \verb\finally\ clause, that finally clause is executed
1480before really leaving the loop.
1481
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001482\section{The \verb\continue\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001483
1484\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001485continue_stmt: "continue"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001486\end{verbatim}
1487
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001488\verb\continue\ may only occur syntactically nested in a \verb\for\ or
1489\verb\while\ loop, not nested in a function or class definition, and
1490not nested in the \verb\try\ clause of a \verb\try\ statement with a
1491\verb\finally\ clause (it may occur nested in a \verb\except\ or
1492\verb\finally\ clause of a \verb\try\ statement though).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001493
1494It continues with the next cycle of the nearest enclosing loop.
1495
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001496\section{The \verb\import\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001497
1498\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001499import_stmt: "import" identifier ("," identifier)*
1500 | "from" identifier "import" identifier ("," identifier)*
1501 | "from" identifier "import" "*"
1502\end{verbatim}
1503
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001504Import statements are executed in two steps: (1) find a module, and
1505initialize it if necessary; (2) define a name or names in the local
1506name space. The first form (without \verb\from\) repeats these steps
1507for each identifier in the list.
Guido van Rossum743d1e71992-01-07 16:43:53 +00001508
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001509The system maintains a table of modules that have been initialized,
1510indexed by module name. (The current implementation makes this table
1511accessible as \verb\sys.modules\.) When a module name is found in
1512this table, step (1) is finished. If not, a search for a module
1513definition is started. This first looks for a built-in module
1514definition, and if no built-in module if the given name is found, it
1515searches a user-specified list of directories for a file whose name is
1516the module name with extension \verb\".py"\. (The current
1517implementation uses the list of strings \verb\sys.path\ as the search
1518path; it is initialized from the shell environment variable
1519\verb\$PYTHONPATH\, with an installation-dependent default.)
1520
1521If a built-in module is found, its built-in initialization code is
1522executed and step (1) is finished. If no matching file is found,
1523\ImportError\ is raised (and step (2) is never started). If a file is
1524found, it is parsed. If a syntax error occurs, HIRO
1525
1526\section{The \verb\global\ statement}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001527
1528\begin{verbatim}
1529global_stmt: "global" identifier ("," identifier)*
Guido van Rossumf2612d11991-11-21 13:53:03 +00001530\end{verbatim}
1531
1532(XXX To be done.)
1533
1534\chapter{Compound statements}
1535
1536(XXX The semantic definitions of this chapter are still to be done.)
1537
1538\begin{verbatim}
1539statement: stmt_list NEWLINE | compound_stmt
1540compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
1541suite: statement | NEWLINE INDENT statement+ DEDENT
1542\end{verbatim}
1543
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001544\section{The \verb\if\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001545
1546\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001547if_stmt: "if" condition ":" suite
1548 ("elif" condition ":" suite)*
1549 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001550\end{verbatim}
1551
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001552\section{The \verb\while\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001553
1554\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001555while_stmt: "while" condition ":" suite ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001556\end{verbatim}
1557
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001558\section{The \verb\for\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001559
1560\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001561for_stmt: "for" target_list "in" condition_list ":" suite
1562 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001563\end{verbatim}
1564
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001565\section{The \verb\try\ statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001566
1567\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001568try_stmt: "try" ":" suite
1569 ("except" condition ["," condition] ":" suite)*
1570 ["finally" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00001571\end{verbatim}
1572
1573\section{Function definitions}
1574
1575\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001576funcdef: "def" identifier "(" [parameter_list] ")" ":" suite
1577parameter_list: parameter ("," parameter)*
1578parameter: identifier | "(" parameter_list ")"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001579\end{verbatim}
1580
1581\section{Class definitions}
1582
1583\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001584classdef: "class" identifier [inheritance] ":" suite
1585inheritance: "(" expression ("," expression)* ")"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001586\end{verbatim}
1587
1588XXX Syntax for scripts, modules
1589XXX Syntax for interactive input, eval, exec, input
Guido van Rossum743d1e71992-01-07 16:43:53 +00001590XXX New definition of expressions (as conditions)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001591
1592\end{document}