blob: 4c9fcaaf7d67446903c8166158375599ab120400 [file] [log] [blame]
Guido van Rossum60279da1992-04-02 10:24:59 +00001\documentstyle[twoside,a4wide,11pt,myformat]{report}
2% ^^^^^^^^^^^^^^^^^^^^
3% If you have trouble finding these style files, any of the pointed-at
4% style options are optional and may be taken out.
5% But "myformat.sty" should be found in the same directory as this file!
6% Also, "myformat" should be last since it corrects a few style params.
Guido van Rossumf2612d11991-11-21 13:53:03 +00007
Guido van Rossum862c6f11992-01-29 14:47:05 +00008\title{\bf Python Reference Manual}
9
Guido van Rossumf2612d11991-11-21 13:53:03 +000010\author{
11 Guido van Rossum \\
12 Dept. CST, CWI, Kruislaan 413 \\
13 1098 SJ Amsterdam, The Netherlands \\
14 E-mail: {\tt guido@cwi.nl}
15}
16
Guido van Rossumb5e1c181992-03-06 10:52:59 +000017% Tell \index to actually write the .idx file
18\makeindex
19
Guido van Rossumf2612d11991-11-21 13:53:03 +000020\begin{document}
21
22\pagenumbering{roman}
23
24\maketitle
25
26\begin{abstract}
27
28\noindent
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000029Python is a simple, yet powerful, interpreted programming language
30that bridges the gap between C and shell programming, and is thus
31ideally suited for ``throw-away programming'' and rapid prototyping.
32Its syntax is put together from constructs borrowed from a variety of
33other languages; most prominent are influences from ABC, C, Modula-3
34and Icon.
Guido van Rossumf2612d11991-11-21 13:53:03 +000035
36The Python interpreter is easily extended with new functions and data
37types implemented in C. Python is also suitable as an extension
38language for highly customizable C applications such as editors or
39window managers.
40
41Python is available for various operating systems, amongst which
42several flavors of {\UNIX}, Amoeba, the Apple Macintosh O.S.,
43and MS-DOS.
44
45This reference manual describes the syntax and ``core semantics'' of
Guido van Rossum0f1f9da1992-01-20 17:10:21 +000046the language. It is terse, but attempts to be exact and complete.
47The semantics of non-essential built-in object types and of the
48built-in functions and modules are described in the {\em Python
49Library Reference}. For an informal introduction to the language, see
50the {\em Python Tutorial}.
Guido van Rossumf2612d11991-11-21 13:53:03 +000051
52\end{abstract}
53
54\pagebreak
55
Guido van Rossum670e5a01992-01-17 14:03:20 +000056{
57\parskip = 0mm
Guido van Rossumf2612d11991-11-21 13:53:03 +000058\tableofcontents
Guido van Rossum670e5a01992-01-17 14:03:20 +000059}
Guido van Rossumf2612d11991-11-21 13:53:03 +000060
61\pagebreak
62
63\pagenumbering{arabic}
64
65\chapter{Introduction}
66
67This reference manual describes the Python programming language.
68It is not intended as a tutorial.
69
Guido van Rossum743d1e71992-01-07 16:43:53 +000070While I am trying to be as precise as possible, I chose to use English
71rather than formal specifications for everything except syntax and
72lexical analysis. This should make the document better understandable
73to the average reader, but will leave room for ambiguities.
74Consequently, if you were coming from Mars and tried to re-implement
Guido van Rossum7b632a61992-01-16 17:49:21 +000075Python from this document alone, you might have to guess things and in
Guido van Rossumb5e1c181992-03-06 10:52:59 +000076fact you would probably end up implementing quite a different language.
Guido van Rossum7b632a61992-01-16 17:49:21 +000077On the other hand, if you are using
Guido van Rossum743d1e71992-01-07 16:43:53 +000078Python and wonder what the precise rules about a particular area of
Guido van Rossumb5e1c181992-03-06 10:52:59 +000079the language are, you should definitely be able to find them here.
Guido van Rossum743d1e71992-01-07 16:43:53 +000080
81It is dangerous to add too many implementation details to a language
Guido van Rossumb5e1c181992-03-06 10:52:59 +000082reference document --- the implementation may change, and other
Guido van Rossum743d1e71992-01-07 16:43:53 +000083implementations of the same language may work differently. On the
84other hand, there is currently only one Python implementation, and
Guido van Rossum7b632a61992-01-16 17:49:21 +000085its particular quirks are sometimes worth being mentioned, especially
Guido van Rossumb5e1c181992-03-06 10:52:59 +000086where the implementation imposes additional limitations. Therefore,
87you'll find short ``implementation notes'' sprinkled throughout the
88text.
Guido van Rossum743d1e71992-01-07 16:43:53 +000089
90Every Python implementation comes with a number of built-in and
91standard modules. These are not documented here, but in the separate
92{\em Python Library Reference} document. A few built-in modules are
93mentioned when they interact in a significant way with the language
94definition.
95
96\section{Notation}
97
98The descriptions of lexical analysis and syntax use a modified BNF
99grammar notation. This uses the following style of definition:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000100\index{BNF}
101\index{grammar}
102\index{syntax}
103\index{notation}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000104
105\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000106name: lc_letter (lc_letter | "_")*
107lc_letter: "a"..."z"
Guido van Rossum743d1e71992-01-07 16:43:53 +0000108\end{verbatim}
109
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000110The first line says that a \verb\name\ is an \verb\lc_letter\ followed by
111a sequence of zero or more \verb\lc_letter\s and underscores. An
112\verb\lc_letter\ in turn is any of the single characters `a' through `z'.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000113(This rule is actually adhered to for the names defined in lexical and
Guido van Rossum743d1e71992-01-07 16:43:53 +0000114grammar rules in this document.)
115
116Each rule begins with a name (which is the name defined by the rule)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000117and a colon. A vertical bar
Guido van Rossum7b632a61992-01-16 17:49:21 +0000118(\verb\|\) is used to separate alternatives; it is the least binding
119operator in this notation. A star (\verb\*\) means zero or more
120repetitions of the preceding item; likewise, a plus (\verb\+\) means
121one or more repetitions, and a question mark (\verb\?\) zero or one
122(in other words, the preceding item is optional). These three
123operators bind as tightly as possible; parentheses are used for
Guido van Rossum743d1e71992-01-07 16:43:53 +0000124grouping. Literal strings are enclosed in double quotes. White space
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000125is only meaningful to separate tokens. Rules are normally contained
126on a single line; rules with many alternatives may be formatted
127alternatively with each line after the first beginning with a
128vertical bar.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000129
130In lexical definitions (as the example above), two more conventions
131are used: Two literal characters separated by three dots mean a choice
132of any single character in the given (inclusive) range of ASCII
133characters. A phrase between angular brackets (\verb\<...>\) gives an
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000134informal description of the symbol defined; e.g. this could be used
Guido van Rossum743d1e71992-01-07 16:43:53 +0000135to describe the notion of `control character' if needed.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000136\index{lexical definitions}
137\index{ASCII}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000138
Guido van Rossum7b632a61992-01-16 17:49:21 +0000139Even though the notation used is almost the same, there is a big
Guido van Rossum743d1e71992-01-07 16:43:53 +0000140difference between the meaning of lexical and syntactic definitions:
141a lexical definition operates on the individual characters of the
142input source, while a syntax definition operates on the stream of
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000143tokens generated by the lexical analysis. All uses of BNF in the next
144chapter (``Lexical Analysis'') are lexical definitions; uses in
145subsequenc chapter are syntactic definitions.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000146
Guido van Rossumf2612d11991-11-21 13:53:03 +0000147\chapter{Lexical analysis}
148
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000149A Python program is read by a {\em parser}. Input to the parser is a
150stream of {\em tokens}, generated by the {\em lexical analyzer}. This
151chapter describes how the lexical analyzer breaks a file into tokens.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000152\index{lexical analysis}
153\index{parser}
154\index{token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000155
156\section{Line structure}
157
Guido van Rossum7b632a61992-01-16 17:49:21 +0000158A Python program is divided in a number of logical lines. The end of
159a logical line is represented by the token NEWLINE. Statements cannot
160cross logical line boundaries except where NEWLINE is allowed by the
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000161syntax (e.g. between statements in compound statements).
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000162\index{line structure}
163\index{logical line}
164\index{NEWLINE token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000165
166\subsection{Comments}
167
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000168A comment starts with a hash character (\verb\#\) that is not part of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000169a string literal, and ends at the end of the physical line. A comment
170always signifies the end of the logical line. Comments are ignored by
171the syntax.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000172\index{comment}
173\index{logical line}
174\index{physical line}
175\index{hash character}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000176
177\subsection{Line joining}
178
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000179Two or more physical lines may be joined into logical lines using
Guido van Rossum7b632a61992-01-16 17:49:21 +0000180backslash characters (\verb/\/), as follows: when a physical line ends
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000181in a backslash that is not part of a string literal or comment, it is
182joined with the following forming a single logical line, deleting the
Guido van Rossum670e5a01992-01-17 14:03:20 +0000183backslash and the following end-of-line character. For example:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000184\index{physical line}
185\index{line joining}
186\index{backslash character}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000187%
188\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000189moth_names = ['Januari', 'Februari', 'Maart', \
190 'April', 'Mei', 'Juni', \
191 'Juli', 'Augustus', 'September', \
192 'Oktober', 'November', 'December']
Guido van Rossum670e5a01992-01-17 14:03:20 +0000193\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000194
195\subsection{Blank lines}
196
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000197A logical line that contains only spaces, tabs, and possibly a
198comment, is ignored (i.e., no NEWLINE token is generated), except that
199during interactive input of statements, an entirely blank logical line
200terminates a multi-line statement.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000201\index{blank line}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000202
203\subsection{Indentation}
204
Guido van Rossum7b632a61992-01-16 17:49:21 +0000205Leading whitespace (spaces and tabs) at the beginning of a logical
206line is used to compute the indentation level of the line, which in
207turn is used to determine the grouping of statements.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000208\index{indentation}
209\index{whitespace}
210\index{leading whitespace}
211\index{space}
212\index{tab}
213\index{grouping}
214\index{statement grouping}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000215
Guido van Rossum7b632a61992-01-16 17:49:21 +0000216First, tabs are replaced (from left to right) by one to eight spaces
217such that the total number of characters up to there is a multiple of
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000218eight (this is intended to be the same rule as used by {\UNIX}). The
Guido van Rossum7b632a61992-01-16 17:49:21 +0000219total number of spaces preceding the first non-blank character then
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000220determines the line's indentation. Indentation cannot be split over
221multiple physical lines using backslashes.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000222
223The indentation levels of consecutive lines are used to generate
224INDENT and DEDENT tokens, using a stack, as follows.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000225\index{INDENT token}
226\index{DEDENT token}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000227
228Before the first line of the file is read, a single zero is pushed on
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000229the stack; this will never be popped off again. The numbers pushed on
230the stack will always be strictly increasing from bottom to top. At
231the beginning of each logical line, the line's indentation level is
232compared to the top of the stack. If it is equal, nothing happens.
233If it larger, it is pushed on the stack, and one INDENT token is
234generated. If it is smaller, it {\em must} be one of the numbers
235occurring on the stack; all numbers on the stack that are larger are
236popped off, and for each number popped off a DEDENT token is
237generated. At the end of the file, a DEDENT token is generated for
238each number remaining on the stack that is larger than zero.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000239
Guido van Rossum7b632a61992-01-16 17:49:21 +0000240Here is an example of a correctly (though confusingly) indented piece
241of Python code:
242
243\begin{verbatim}
244def perm(l):
Guido van Rossum670e5a01992-01-17 14:03:20 +0000245 # Compute the list of all permutations of l
246
Guido van Rossum7b632a61992-01-16 17:49:21 +0000247 if len(l) <= 1:
248 return [l]
249 r = []
250 for i in range(len(l)):
251 s = l[:i] + l[i+1:]
252 p = perm(s)
253 for x in p:
254 r.append(l[i:i+1] + x)
255 return r
256\end{verbatim}
257
258The following example shows various indentation errors:
259
260\begin{verbatim}
261 def perm(l): # error: first line indented
262 for i in range(len(l)): # error: not indented
263 s = l[:i] + l[i+1:]
264 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
265 for x in p:
266 r.append(l[i:i+1] + x)
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000267 return r # error: inconsistent dedent
Guido van Rossum7b632a61992-01-16 17:49:21 +0000268\end{verbatim}
269
270(Actually, the first three errors are detected by the parser; only the
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000271last error is found by the lexical analyzer --- the indentation of
Guido van Rossum7b632a61992-01-16 17:49:21 +0000272\verb\return r\ does not match a level popped off the stack.)
273
Guido van Rossumf2612d11991-11-21 13:53:03 +0000274\section{Other tokens}
275
276Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
277exist: identifiers, keywords, literals, operators, and delimiters.
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000278Spaces and tabs are not tokens, but serve to delimit tokens. Where
279ambiguity exists, a token comprises the longest possible string that
280forms a legal token, when read from left to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000281
Guido van Rossumf2612d11991-11-21 13:53:03 +0000282\section{Identifiers}
283
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000284Identifiers (also referred to as names) are described by the following
285lexical definitions:
286\index{identifier}
287\index{name}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000288
289\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000290identifier: (letter|"_") (letter|digit|"_")*
Guido van Rossumf2612d11991-11-21 13:53:03 +0000291letter: lowercase | uppercase
Guido van Rossum743d1e71992-01-07 16:43:53 +0000292lowercase: "a"..."z"
293uppercase: "A"..."Z"
294digit: "0"..."9"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000295\end{verbatim}
296
Guido van Rossum670e5a01992-01-17 14:03:20 +0000297Identifiers are unlimited in length. Case is significant.
Guido van Rossumf2612d11991-11-21 13:53:03 +0000298
Guido van Rossum670e5a01992-01-17 14:03:20 +0000299\subsection{Keywords}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000300
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000301The following identifiers are used as reserved words, or {\em
Guido van Rossum7b632a61992-01-16 17:49:21 +0000302keywords} of the language, and cannot be used as ordinary
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000303identifiers. They must be spelled exactly as written here:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000304\index{keyword}
305\index{reserved word}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000306
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000307\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000308and del for in print
309break elif from is raise
310class else global not return
311continue except if or try
312def finally import pass while
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000313\end{verbatim}
314
Guido van Rossum743d1e71992-01-07 16:43:53 +0000315% # This Python program sorts and formats the above table
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000316% import string
317% l = []
318% try:
319% while 1:
320% l = l + string.split(raw_input())
321% except EOFError:
322% pass
323% l.sort()
324% for i in range((len(l)+4)/5):
325% for j in range(i, len(l), 5):
326% print string.ljust(l[j], 10),
327% print
Guido van Rossumf2612d11991-11-21 13:53:03 +0000328
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000329\section{Literals} \label{literals}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000330
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000331Literals are notations for constant values of some built-in types.
332\index{literal}
333\index{constant}
334
Guido van Rossumf2612d11991-11-21 13:53:03 +0000335\subsection{String literals}
336
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000337String literals are described by the following lexical definitions:
338\index{string literal}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000339
340\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000341stringliteral: "'" stringitem* "'"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000342stringitem: stringchar | escapeseq
Guido van Rossum743d1e71992-01-07 16:43:53 +0000343stringchar: <any ASCII character except newline or "\" or "'">
344escapeseq: "'" <any ASCII character except newline>
Guido van Rossumf2612d11991-11-21 13:53:03 +0000345\end{verbatim}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000346\index{ASCII}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000347
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000348String literals cannot span physical line boundaries. Escape
349sequences in strings are actually interpreted according to rules
350simular to those used by Standard C. The recognized escape sequences
351are:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000352\index{physical line}
353\index{escape sequence}
354\index{Standard C}
355\index{C}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000356
357\begin{center}
358\begin{tabular}{|l|l|}
359\hline
360\verb/\\/ & Backslash (\verb/\/) \\
361\verb/\'/ & Single quote (\verb/'/) \\
362\verb/\a/ & ASCII Bell (BEL) \\
363\verb/\b/ & ASCII Backspace (BS) \\
Guido van Rossum7b632a61992-01-16 17:49:21 +0000364%\verb/\E/ & ASCII Escape (ESC) \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000365\verb/\f/ & ASCII Formfeed (FF) \\
366\verb/\n/ & ASCII Linefeed (LF) \\
367\verb/\r/ & ASCII Carriage Return (CR) \\
368\verb/\t/ & ASCII Horizontal Tab (TAB) \\
369\verb/\v/ & ASCII Vertical Tab (VT) \\
370\verb/\/{\em ooo} & ASCII character with octal value {\em ooo} \\
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000371\verb/\x/{\em xx...} & ASCII character with hex value {\em xx...} \\
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000372\hline
373\end{tabular}
374\end{center}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000375\index{ASCII}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000376
Guido van Rossum7b632a61992-01-16 17:49:21 +0000377In strict compatibility with in Standard C, up to three octal digits are
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000378accepted, but an unlimited number of hex digits is taken to be part of
379the hex escape (and then the lower 8 bits of the resulting hex number
Guido van Rossum7b632a61992-01-16 17:49:21 +0000380are used in all current implementations...).
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000381
Guido van Rossum7b632a61992-01-16 17:49:21 +0000382All unrecognized escape sequences are left in the string unchanged,
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000383i.e., {\em the backslash is left in the string.} (This behavior is
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000384useful when debugging: if an escape sequence is mistyped, the
Guido van Rossum743d1e71992-01-07 16:43:53 +0000385resulting output is more easily recognized as broken. It also helps a
386great deal for string literals used as regular expressions or
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000387otherwise passed to other modules that do their own escape handling.)
388\index{unrecognized escape sequence}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000389
390\subsection{Numeric literals}
391
Guido van Rossum670e5a01992-01-17 14:03:20 +0000392There are three types of numeric literals: plain integers, long
393integers, and floating point numbers.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000394\index{number}
395\index{numeric literal}
396\index{integer literal}
397\index{plain integer literal}
398\index{long integer literal}
399\index{floating point literal}
400\index{hexadecimal literal}
401\index{octal literal}
402\index{decimal literal}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000403
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000404Integer and long integer literals are described by the following
405lexical definitions:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000406
407\begin{verbatim}
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000408longinteger: integer ("l"|"L")
Guido van Rossumf2612d11991-11-21 13:53:03 +0000409integer: decimalinteger | octinteger | hexinteger
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000410decimalinteger: nonzerodigit digit* | "0"
411octinteger: "0" octdigit+
412hexinteger: "0" ("x"|"X") hexdigit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000413
Guido van Rossum743d1e71992-01-07 16:43:53 +0000414nonzerodigit: "1"..."9"
415octdigit: "0"..."7"
416hexdigit: digit|"a"..."f"|"A"..."F"
Guido van Rossumf2612d11991-11-21 13:53:03 +0000417\end{verbatim}
418
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000419Although both lower case `l' and upper case `L' are allowed as suffix
Guido van Rossum670e5a01992-01-17 14:03:20 +0000420for long integers, it is strongly recommended to always use `L', since
421the letter `l' looks too much like the digit `1'.
422
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000423Plain integer decimal literals must be at most $2^{31} - 1$ (i.e., the
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000424largest positive integer, assuming 32-bit arithmetic). Plain octal and
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000425hexadecimal literals may be as large as $2^{32} - 1$, but values
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000426larger than $2^{31} - 1$ are converted to a negative value by
427subtracting $2^{32}$. There is no limit for long integer literals.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000428
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000429Some examples of plain and long integer literals:
Guido van Rossum670e5a01992-01-17 14:03:20 +0000430
431\begin{verbatim}
4327 2147483647 0177 0x80000000
Guido van Rossumb5e1c181992-03-06 10:52:59 +00004333L 79228162514264337593543950336L 0377L 0x100000000L
Guido van Rossum670e5a01992-01-17 14:03:20 +0000434\end{verbatim}
435
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000436Floating point literals are described by the following lexical
437definitions:
Guido van Rossumf2612d11991-11-21 13:53:03 +0000438
439\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +0000440floatnumber: pointfloat | exponentfloat
441pointfloat: [intpart] fraction | intpart "."
442exponentfloat: (intpart | pointfloat) exponent
Guido van Rossumf2612d11991-11-21 13:53:03 +0000443intpart: digit+
Guido van Rossum4fc43bc1991-11-25 17:26:57 +0000444fraction: "." digit+
445exponent: ("e"|"E") ["+"|"-"] digit+
Guido van Rossumf2612d11991-11-21 13:53:03 +0000446\end{verbatim}
447
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000448The allowed range of floating point literals is
449implementation-dependent.
Guido van Rossum670e5a01992-01-17 14:03:20 +0000450
451Some examples of floating point literals:
Guido van Rossum7b632a61992-01-16 17:49:21 +0000452
453\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00004543.14 10. .001 1e100 3.14e-10
Guido van Rossum7b632a61992-01-16 17:49:21 +0000455\end{verbatim}
456
Guido van Rossum670e5a01992-01-17 14:03:20 +0000457Note that numeric literals do not include a sign; a phrase like
458\verb\-1\ is actually an expression composed of the operator
Guido van Rossum7b632a61992-01-16 17:49:21 +0000459\verb\-\ and the literal \verb\1\.
460
Guido van Rossumf2612d11991-11-21 13:53:03 +0000461\section{Operators}
462
463The following tokens are operators:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000464\index{operators}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000465
466\begin{verbatim}
467+ - * / %
468<< >> & | ^ ~
Guido van Rossum743d1e71992-01-07 16:43:53 +0000469< == > <= <> != >=
Guido van Rossumf2612d11991-11-21 13:53:03 +0000470\end{verbatim}
471
Guido van Rossum743d1e71992-01-07 16:43:53 +0000472The comparison operators \verb\<>\ and \verb\!=\ are alternate
473spellings of the same operator.
474
Guido van Rossumf2612d11991-11-21 13:53:03 +0000475\section{Delimiters}
476
Guido van Rossum743d1e71992-01-07 16:43:53 +0000477The following tokens serve as delimiters or otherwise have a special
478meaning:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000479\index{delimiters}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000480
481\begin{verbatim}
482( ) [ ] { }
Guido van Rossum743d1e71992-01-07 16:43:53 +0000483; , : . ` =
Guido van Rossumf2612d11991-11-21 13:53:03 +0000484\end{verbatim}
485
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000486The following printing ASCII characters are not used in Python. Their
487occurrence outside string literals and comments is an unconditional
488error:
489\index{ASCII}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000490
491\begin{verbatim}
492! @ $ " ?
493\end{verbatim}
494
Guido van Rossum7b632a61992-01-16 17:49:21 +0000495They may be used by future versions of the language though!
496
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000497\chapter{Data model}
Guido van Rossumf2612d11991-11-21 13:53:03 +0000498
Guido van Rossum743d1e71992-01-07 16:43:53 +0000499\section{Objects, values and types}
500
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000501{\em Objects} are Python's abstraction for data. All data in a Python
502program is represented by objects or by relations between objects.
503(In a sense, and in conformance to Von Neumann's model of a
504``stored program computer'', code is also represented by objects.)
505\index{object}
506\index{data}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000507
508Every object has an identity, a type and a value. An object's {\em
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000509identity} never changes once it has been created; you may think of it
510as the object's address in memory. An object's {\em type} is also
511unchangeable. It determines the operations that an object supports
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000512(e.g. ``does it have a length?'') and also defines the possible
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000513values for objects of that type. The {\em value} of some objects can
514change. Objects whose value can change are said to be {\em mutable};
515objects whose value is unchangeable once they are created are called
516{\em immutable}. The type determines an object's (im)mutability.
517\index{identity of an object}
518\index{value of an object}
519\index{type of an object}
520\index{mutable object}
521\index{immutable object}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000522
523Objects are never explicitly destroyed; however, when they become
Guido van Rossum670e5a01992-01-17 14:03:20 +0000524unreachable they may be garbage-collected. An implementation is
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000525allowed to delay garbage collection or omit it altogether --- it is a
Guido van Rossum670e5a01992-01-17 14:03:20 +0000526matter of implementation quality how garbage collection is
527implemented, as long as no objects are collected that are still
528reachable. (Implementation note: the current implementation uses a
Guido van Rossum743d1e71992-01-07 16:43:53 +0000529reference-counting scheme which collects most objects as soon as they
Guido van Rossum0f1f9da1992-01-20 17:10:21 +0000530become unreachable, but never collects garbage containing circular
Guido van Rossum743d1e71992-01-07 16:43:53 +0000531references.)
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000532\index{garbage collection}
533\index{reference counting}
534\index{unreachable object}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000535
Guido van Rossum670e5a01992-01-17 14:03:20 +0000536Note that the use of the implementation's tracing or debugging
537facilities may keep objects alive that would normally be collectable.
538
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000539Some objects contain references to ``external'' resources such as open
540files or windows. It is understood that these resources are freed
541when the object is garbage-collected, but since garbage collection is
542not guaranteed to happen, such objects also provide an explicit way to
543release the external resource, usually a \verb\close\ method.
544Programs are strongly recommended to always explicitly close such
545objects.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000546
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000547Some objects contain references to other objects; these are called
548{\em containers}. Examples of containers are tuples, lists and
549dictionaries. The references are part of a container's value. In
550most cases, when we talk about the value of a container, we imply the
551values, not the identities of the contained objects; however, when we
552talk about the (im)mutability of a container, only the identities of
553the immediately contained objects are implied. (So, if an immutable
554container contains a reference to a mutable object, its value changes
555if that mutable object is changed.)
556\index{container}
Guido van Rossum743d1e71992-01-07 16:43:53 +0000557
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000558Types affect almost all aspects of objects' lives. Even the meaning
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000559of object identity is affected in some sense: for immutable types,
560operations that compute new values may actually return a reference to
561any existing object with the same type and value, while for mutable
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000562objects this is not allowed. E.g. after
Guido van Rossum743d1e71992-01-07 16:43:53 +0000563
564\begin{verbatim}
565a = 1; b = 1; c = []; d = []
566\end{verbatim}
567
Guido van Rossumcf8148b1992-03-02 16:13:50 +0000568\verb\a\ and \verb\b\ may or may not refer to the same object with the
569value one, depending on the implementation, but \verb\c\ and \verb\d\
570are guaranteed to refer to two different, unique, newly created empty
571lists.
Guido van Rossum743d1e71992-01-07 16:43:53 +0000572
Guido van Rossum60279da1992-04-02 10:24:59 +0000573\section{The standard type hierarchy} \label{types}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000574
575Below is a list of the types that are built into Python. Extension
576modules written in C can define additional types. Future versions of
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000577Python may add types to the type hierarchy (e.g. rational or complex
Guido van Rossumcb9d66d1992-03-20 14:59:04 +0000578numbers, efficiently stored arrays of integers, etc.).
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000579\index{type}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000580\indexii{data}{type}
581\indexii{type}{hierarchy}
582\indexii{extension}{module}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000583\index{C}
584
585Some of the type descriptions below contain a paragraph listing
586`special attributes'. These are attributes that provide access to the
587implementation and are not intended for general use. Their definition
588may change in the future. There are also some `generic' special
589attributes, not listed with the individual objects: \verb\__methods__\
590is a list of the method names of a built-in object, if it has any;
591\verb\__members__\ is a list of the data attribute names of a built-in
592object, if it has any.
593\index{attribute}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000594\indexii{special}{attribute}
595\indexiii{generic}{special}{attribute}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000596\ttindex{__methods__}
597\ttindex{__members__}
598
599\begin{description}
600
601\item[None]
602This type has a single value. There is a single object with this value.
603This object is accessed through the built-in name \verb\None\.
604It is returned from functions that don't explicitly return an object.
605\ttindex{None}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000606\obindex{None@{\tt None}}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000607
608\item[Numbers]
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000609These are created by numeric literals and returned as results by
610arithmetic operators and arithmetic built-in functions. Numeric
611objects are immutable; once created their value never changes. Python
612numbers are of course strongly related to mathematical numbers, but
613subject to the limitations of numerical representation in computers.
614\obindex{number}
615\obindex{numeric}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000616
617Python distinguishes between integers and floating point numbers:
618
619\begin{description}
620\item[Integers]
621These represent elements from the mathematical set of whole numbers.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000622\obindex{integer}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000623
624There are two types of integers:
625
626\begin{description}
627
628\item[Plain integers]
629These represent numbers in the range $-2^{31}$ through $2^{31}-1$.
630(The range may be larger on machines with a larger natural word
631size, but not smaller.)
632When the result of an operation falls outside this range, the
633exception \verb\OverflowError\ is raised.
634For the purpose of shift and mask operations, integers are assumed to
635have a binary, 2's complement notation using 32 or more bits, and
636hiding no bits from the user (i.e., all $2^{32}$ different bit
637patterns correspond to different values).
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000638\obindex{plain integer}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000639
640\item[Long integers]
641These represent numbers in an unlimited range, subject to avaiable
642(virtual) memory only. For the purpose of shift and mask operations,
643a binary representation is assumed, and negative numbers are
644represented in a variant of 2's complement which gives the illusion of
645an infinite string of sign bits extending to the left.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000646\obindex{long integer}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000647
648\end{description} % Integers
649
650The rules for integer representation are intended to give the most
651meaningful interpretation of shift and mask operations involving
652negative integers and the least surprises when switching between the
653plain and long integer domains. For any operation except left shift,
654if it yields a result in the plain integer domain without causing
655overflow, it will yield the same result in the long integer domain or
656when using mixed operands.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000657\indexii{integer}{representation}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000658
659\item[Floating point numbers]
660These represent machine-level double precision floating point numbers.
661You are at the mercy of the underlying machine architecture and
662C implementation for the accepted range and handling of overflow.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000663\obindex{floating point}
664\indexii{floating point}{number}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000665\index{C}
666
667\end{description} % Numbers
668
669\item[Sequences]
670These represent finite ordered sets indexed by natural numbers.
671The built-in function \verb\len()\ returns the number of elements
672of a sequence. When this number is $n$, the index set contains
673the numbers $0, 1, \ldots, n-1$. Element \verb\i\ of sequence
674\verb\a\ is selected by \verb\a[i]\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000675\obindex{seqence}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000676\bifuncindex{len}
677\index{index operation}
678\index{item selection}
679\index{subscription}
680
681Sequences also support slicing: \verb\a[i:j]\ selects all elements
682with index $k$ such that $i < k < j$. When used as an expression,
683a slice is a sequence of the same type --- this implies that the
684index set is renumbered so that it starts at 0 again.
685\index{slicing}
686
687Sequences are distinguished according to their mutability:
688
689\begin{description}
690%
691\item[Immutable sequences]
692An object of an immutable sequence type cannot change once it is
693created. (If the object contains references to other objects,
694these other objects may be mutable and may be changed; however
695the collection of objects directly referenced by an immutable object
696cannot change.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000697\obindex{immutable sequence}
698\obindex{immutable}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000699
700The following types are immutable sequences:
701
702\begin{description}
703
704\item[Strings]
705The elements of a string are characters. There is no separate
706character type; a character is represented by a string of one element.
707Characters represent (at least) 8-bit bytes. The built-in
708functions \verb\chr()\ and \verb\ord()\ convert between characters
709and nonnegative integers representing the byte values.
710Bytes with the values 0-127 represent the corresponding ASCII values.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000711The string data type is also used to represent arrays of bytes, e.g.
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000712to hold data read from a file.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000713\obindex{string}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000714\index{character}
715\index{byte}
716\index{ASCII}
717\bifuncindex{chr}
718\bifuncindex{ord}
719
720(On systems whose native character set is not ASCII, strings may use
721EBCDIC in their internal representation, provided the functions
722\verb\chr()\ and \verb\ord()\ implement a mapping between ASCII and
723EBCDIC, and string comparison preserves the ASCII order.
724Or perhaps someone can propose a better rule?)
725\index{ASCII}
726\index{EBCDIC}
727\index{character set}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000728\indexii{string}{comparison}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000729\bifuncindex{chr}
730\bifuncindex{ord}
731
732\item[Tuples]
733The elements of a tuple are arbitrary Python objects.
734Tuples of two or more elements are formed by comma-separated lists
735of expressions. A tuple of one element (a `singleton') can be formed
736by affixing a comma to an expression (an expression by itself does
737not create a tuple, since parentheses must be usable for grouping of
738expressions). An empty tuple can be formed by enclosing `nothing' in
739parentheses.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000740\obindex{tuple}
741\indexii{singleton}{tuple}
742\indexii{empty}{tuple}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000743
744\end{description} % Immutable sequences
745
746\item[Mutable sequences]
747Mutable sequences can be changed after they are created. The
748subscription and slicing notations can be used as the target of
749assignment and \verb\del\ (delete) statements.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000750\obindex{mutable sequece}
751\obindex{mutable}
752\indexii{assignment}{statement}
753\index{delete}
754\stindex{del}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000755\index{subscription}
756\index{slicing}
757
758There is currently a single mutable sequence type:
759
760\begin{description}
761
762\item[Lists]
763The elements of a list are arbitrary Python objects. Lists are formed
764by placing a comma-separated list of expressions in square brackets.
765(Note that there are no special cases needed to form lists of length 0
766or 1.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000767\obindex{list}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000768
769\end{description} % Mutable sequences
770
771\end{description} % Sequences
772
773\item[Mapping types]
774These represent finite sets of objects indexed by arbitrary index sets.
775The subscript notation \verb\a[k]\ selects the element indexed
776by \verb\k\ from the mapping \verb\a\; this can be used in
777expressions and as the target of assignments or \verb\del\ statements.
778The built-in function \verb\len()\ returns the number of elements
779in a mapping.
780\bifuncindex{len}
781\index{subscription}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000782\obindex{mapping}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000783
784There is currently a single mapping type:
785
786\begin{description}
787
788\item[Dictionaries]
789These represent finite sets of objects indexed by strings.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000790Dictionaries are mutable; they are created by the \verb\{...}\
791notation (see section \ref{dict}). (Implementation note: the strings
792used for indexing must not contain null bytes.)
793\obindex{dictionary}
794\obindex{mutable}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000795
796\end{description} % Mapping types
797
798\item[Callable types]
799These are the types to which the function call (invocation) operation,
800written as \verb\function(argument, argument, ...)\, can be applied:
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000801\indexii{function}{call}
802\index{invocation}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000803\indexii{function}{argument}
804\obindex{callable}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000805
806\begin{description}
807
808\item[User-defined functions]
809A user-defined function object is created by a function definition
810(see section \ref{function}). It should be called with an argument
811list containing the same number of items as the function's formal
812parameter list.
813\indexii{user-defined}{function}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000814\obindex{function}
815\obindex{user-defined function}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000816
817Special read-only attributes: \verb\func_code\ is the code object
818representing the compiled function body, and \verb\func_globals\ is (a
819reference to) the dictionary that holds the function's global
820variables --- it implements the global name space of the module in
821which the function was defined.
822\ttindex{func_code}
823\ttindex{func_globals}
824\indexii{global}{name space}
825
826\item[User-defined methods]
Guido van Rossum60279da1992-04-02 10:24:59 +0000827A user-defined method (a.k.a. {\em object closure}) is a pair of a
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000828class instance object and a user-defined function. It should be
829called with an argument list containing one item less than the number
830of items in the function's formal parameter list. When called, the
831class instance becomes the first argument, and the call arguments are
832shifted one to the right.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000833\obindex{method}
834\obindex{user-defined method}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000835indexii{user-defined}{method}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000836\index{object closure}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000837
838Special read-only attributes: \verb\im_self\ is the class instance
839object, \verb\im_func\ is the function object.
840\ttindex{im_func}
841\ttindex{im_self}
842
843\item[Built-in functions]
844A built-in function object is a wrapper around a C function. Examples
845of built-in functions are \verb\len\ and \verb\math.sin\. There
846are no special attributes. The number and type of the arguments are
847determined by the C function.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000848\obindex{built-in function}
849\obindex{function}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000850\index{C}
851
852\item[Built-in methods]
853This is really a different disguise of a built-in function, this time
854containing an object passed to the C function as an implicit extra
855argument. An example of a built-in method is \verb\list.append\ if
856\verb\list\ is a list object.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000857\obindex{built-in method}
858\obindex{method}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000859\indexii{built-in}{method}
860
861\item[Classes]
862Class objects are described below. When a class object is called as a
863parameterless function, a new class instance (also described below) is
864created and returned. The class's initialization function is not
865called --- this is the responsibility of the caller. It is illegal to
866call a class object with one or more arguments.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000867\obindex{class}
868\obindex{class instance}
869\obindex{instance}
870\indexii{class object}{call}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000871
872\end{description}
873
874\item[Modules]
875Modules are imported by the \verb\import\ statement (see section
876\ref{import}). A module object is a container for a module's name
877space, which is a dictionary (the same dictionary as referenced by the
878\verb\func_globals\ attribute of functions defined in the module).
879Module attribute references are translated to lookups in this
880dictionary. A module object does not contain the code object used to
881initialize the module (since it isn't needed once the initialization
882is done).
883\stindex{import}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000884\obindex{module}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000885
886Attribute assignment update the module's name space dictionary.
887
888Special read-only attributes: \verb\__dict__\ yields the module's name
889space as a dictionary object; \verb\__name__\ yields the module's name
890as a string object.
891\ttindex{__dict__}
892\ttindex{__name__}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000893\indexii{module}{name space}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000894
895\item[Classes]
896Class objects are created by class definitions (see section
897\ref{class}). A class is a container for a dictionary containing the
898class's name space. Class attribute references are translated to
899lookups in this dictionary. When an attribute name is not found
900there, the attribute search continues in the base classes. The search
901is depth-first, left-to-right in the order of their occurrence in the
902base class list.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000903\obindex{class}
904\obindex{class instance}
905\obindex{instance}
906\indexii{class object}{call}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000907\index{container}
908\index{dictionary}
909\indexii{class}{attribute}
910
911Class attribute assignments update the class's dictionary, never the
912dictionary of a base class.
913\indexiii{class}{attribute}{assignment}
914
915A class can be called as a parameterless function to yield a class
916instance (see above).
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000917\indexii{class object}{call}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000918
919Special read-only attributes: \verb\__dict__\ yields te dictionary
920containing the class's name space; \verb\__bases__\ yields a tuple
921(possibly empty or a singleton) containing the base classes, in the
922order of their occurrence in the base class list.
923\ttindex{__dict__}
924\ttindex{__bases__}
925
926\item[Class instances]
927A class instance is created by calling a class object as a
928parameterless function. A class instance has a dictionary in which
929attribute references are searched. When an attribute is not found
930there, and the instance's class has an attribute by that name, and
931that class attribute is a user-defined function (and in no other
932cases), the instance attribute reference yields a user-defined method
933object (see above) constructed from the instance and the function.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000934\obindex{class instance}
935\obindex{instance}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000936\indexii{class}{instance}
937\indexii{class instance}{attribute}
938
939Attribute assignments update the instance's dictionary.
940\indexiii{class instance}{attribute}{assignment}
941
942Special read-only attributes: \verb\__dict__\ yields the attribute
943dictionary; \verb\__class__\ yields the instance's class.
944\ttindex{__dict__}
945\ttindex{__class__}
946
947\item[Files]
948A file object represents an open file. (It is a wrapper around a C
949{\tt stdio} file pointer.) File objects are created by the
950\verb\open()\ built-in function, and also by \verb\posix.popen()\ and
951the \verb\makefile\ method of socket objects. \verb\sys.stdin\,
952\verb\sys.stdout\ and \verb\sys.stderr\ are file objects corresponding
953the the interpreter's standard input, output and error streams.
954See the Python Library Reference for methods of file objects and other
955details.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000956\obindex{file}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000957\index{C}
958\index{stdio}
959\bifuncindex{open}
960\bifuncindex{popen}
961\bifuncindex{makefile}
962\ttindex{stdin}
963\ttindex{stdout}
964\ttindex{stderr}
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000965\ttindex{sys.stdin}
966\ttindex{sys.stdout}
967\ttindex{sys.stderr}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000968
969\item[Internal types]
970A few types used internally by the interpreter are exposed to the user.
971Their definition may change with future versions of the interpreter,
972but they are mentioned here for completeness.
973\index{internal type}
974
975\begin{description}
976
977\item[Code objects]
978Code objects represent executable code. The difference between a code
979object and a function object is that the function object contains an
980explicit reference to the function's context (the module in which it
981was defined) which a code object contains no context. There is no way
982to execute a bare code object.
Guido van Rossum2974e3b1992-04-03 14:44:05 +0000983\obindex{code}
Guido van Rossumb5e1c181992-03-06 10:52:59 +0000984
985Special read-only attributes: \verb\co_code\ is a string representing
986the sequence of instructions; \verb\co_consts\ is a list of literals
987used by the code; \verb\co_names\ is a list of names (strings) used by
988the code; \verb\co_filename\ is the filename from which the code was
989compiled. (To find out the line numbers, you would have to decode the
990instructions; the standard library module \verb\dis\ contains an
991example of how to do this.)
992\ttindex{co_code}
993\ttindex{co_consts}
994\ttindex{co_names}
995\ttindex{co_filename}
996
997\item[Frame objects]
998Frame objects represent execution frames. They may occur in traceback
999objects (see below).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001000\obindex{frame}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001001
1002Special read-only attributes: \verb\f_back\ is to the previous
1003stack frame (towards the caller), or \verb\None\ if this is the bottom
1004stack frame; \verb\f_code\ is the code object being executed in this
1005frame; \verb\f_globals\ is the dictionary used to look up global
1006variables; \verb\f_locals\ is used for local variables;
1007\verb\f_lineno\ gives the line number and \verb\f_lasti\ gives the
1008precise instruction (this is an index into the instruction string of
1009the code object).
1010\ttindex{f_back}
1011\ttindex{f_code}
1012\ttindex{f_globals}
1013\ttindex{f_locals}
1014\ttindex{f_lineno}
1015\ttindex{f_lasti}
1016
1017\item[Traceback objects]
1018Traceback objects represent a stack trace of an exception. A
1019traceback object is created when an exception occurs. When the search
1020for an exception handler unwinds the execution stack, at each unwound
1021level a traceback object is inserted in front of the current
1022traceback. When an exception handler is entered, the stack trace is
1023made available to the program as \verb\sys.exc_traceback\. When the
1024program contains no suitable handler, the stack trace is written
1025(nicely formatted) to the standard error stream; if the interpreter is
1026interactive, it is also made available to the user as
1027\verb\sys.last_traceback\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001028\obindex{traceback}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001029\indexii{stack}{trace}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001030\indexii{exception}{handler}
1031\indexii{execution}{stack}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001032\ttindex{exc_traceback}
1033\ttindex{last_traceback}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001034\ttindex{sys.exc_traceback}
1035\ttindex{sys.last_traceback}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001036
1037Special read-only attributes: \verb\tb_next\ is the next level in the
1038stack trace (towards the frame where the exception occurred), or
1039\verb\None\ if there is no next level; \verb\tb_frame\ points to the
1040execution frame of the current level; \verb\tb_lineno\ gives the line
1041number where the exception occurred; \verb\tb_lasti\ indicates the
1042precise instruction. The line number and last instruction in the
1043traceback may differ from the line number of its frame object if the
1044exception occurred in a \verb\try\ statement with no matching
1045\verb\except\ clause or with a \verb\finally\ clause.
1046\ttindex{tb_next}
1047\ttindex{tb_frame}
1048\ttindex{tb_lineno}
1049\ttindex{tb_lasti}
1050\stindex{try}
1051
1052\end{description} % Internal types
1053
1054\end{description} % Types
1055
1056\chapter{Execution model}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001057\index{execution model}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001058
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001059\section{Code blocks, execution frames, and name spaces} \label{execframes}
1060\index{code block}
1061\indexii{execution}{frame}
1062\index{name space}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001063
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001064A {\em code block} is a piece of Python program text that can be
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001065executed as a unit, such as a module, a class definition or a function
1066body. Some code blocks (like modules) are executed only once, others
1067(like function bodies) may be executed many times. Code block may
1068textually contain other code blocks. Code blocks may invoke other
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001069code blocks (that may or may not be textually contained in them) as
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001070part of their execution, e.g. by invoking (calling) a function.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001071\index{code block}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001072\indexii{code}{block}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001073
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001074The following are code blocks: A module is a code block. A function
1075body is a code block. A class definition is a code block. Each
1076command typed interactively is a separate code block; a script file is
1077a code block. The string argument passed to the built-in functions
1078\verb\eval\ and \verb\exec\ are code blocks. And finally, the
1079expression read and evaluated by the built-in function \verb\input\ is
1080a code block.
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001081
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001082A code block is executed in an execution frame. An {\em execution
1083frame} contains some administrative information (used for debugging),
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001084determines where and how execution continues after the code block's
1085execution has completed, and (perhaps most importantly) defines two
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001086name spaces, the local and the global name space, that affect
1087execution of the code block.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001088\indexii{execution}{frame}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001089
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001090A {\em name space} is a mapping from names (identifiers) to objects.
1091A particular name space may be referenced by more than one execution
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001092frame, and from other places as well. Adding a name to a name space
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001093is called {\em binding} a name (to an object); changing the mapping of
1094a name is called {\em rebinding}; removing a name is {\em unbinding}.
1095Name spaces are functionally equivalent to dictionaries.
1096\index{name space}
1097\indexii{binding}{name}
1098\indexii{rebinding}{name}
1099\indexii{unbinding}{name}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001100
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001101The {\em local name space} of an execution frame determines the default
1102place where names are defined and searched. The {\em global name
1103space} determines the place where names listed in \verb\global\
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001104statements are defined and searched, and where names that are not
1105explicitly bound in the current code block are searched.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001106\indexii{local}{name space}
1107\indexii{global}{name space}
1108\stindex{global}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001109
1110Whether a name is local or global in a code block is determined by
1111static inspection of the source text for the code block: in the
1112absence of \verb\global\ statements, a name that is bound anywhere in
1113the code block is local in the entire code block; all other names are
1114considered global. The \verb\global\ statement forces global
1115interpretation of selected names throughout the code block. The
1116following constructs bind names: formal parameters, \verb\import\
1117statements, class and function definitions (these bind the class or
1118function name), and targets that are identifiers if occurring in an
1119assignment, \verb\for\ loop header, or \verb\except\ clause header.
1120(A target occurring in a \verb\del\ statement does not bind a name.)
1121
1122When a global name is not found in the global name space, it is
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001123searched in the list of ``built-in'' names (which is actually the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001124global name space of the module \verb\builtin\). When a name is not
1125found at all, the \verb\NameError\ exception is raised.
1126
1127The following table lists the meaning of the local and global name
1128space for various types of code blocks. The name space for a
1129particular module is automatically created when the module is first
1130referenced.
1131
1132\begin{center}
1133\begin{tabular}{|l|l|l|l|}
1134\hline
1135Code block type & Global name space & Local name space & Notes \\
1136\hline
1137Module & n.s. for this module & same as global & \\
1138Script & n.s. for \verb\__main__\ & same as global & \\
1139Interactive command & n.s. for \verb\__main__\ & same as global & \\
1140Class definition & global n.s. of containing block & new n.s. & \\
1141Function body & global n.s. of containing block & new n.s. & \\
1142String passed to \verb\exec\ or \verb\eval\
1143 & global n.s. of caller & local n.s. of caller & (1) \\
1144File read by \verb\execfile\
1145 & global n.s. of caller & local n.s. of caller & (1) \\
1146Expression read by \verb\input\
1147 & global n.s. of caller & local n.s. of caller & \\
1148\hline
1149\end{tabular}
1150\end{center}
1151
1152Notes:
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001153
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001154\begin{description}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001155
1156\item[n.s.] means {\em name space}
1157
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001158\item[(1)] The global and local name space for these functions can be
1159overridden with optional extra arguments.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001160
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001161\end{description}
1162
1163\section{Exceptions}
1164
1165Exceptions are a means of breaking out of the normal flow of control
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001166of a code block in order to handle errors or other exceptional
1167conditions. An exception is {\em raised} at the point where the error
1168is detected; it may be {\em handled} by the surrounding code block or
1169by any code block that directly or indirectly invoked the code block
1170where the error occurred.
1171\index{exception}
1172\index{raise an exception}
1173\index{handle an exception}
1174\index{exception handler}
1175\index{errors}
1176\index{error handling}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001177
1178The Python interpreter raises an exception when it detects an run-time
1179error (such as division by zero). A Python program can also
1180explicitly raise an exception with the \verb\raise\ statement.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001181Exception handlers are specified with the \verb\try...except\
1182statement.
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001183
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001184Python uses the ``termination'' model of error handling: an exception
1185handler can find out what happened and continue execution at an outer
1186level, but it cannot repair the cause of the error and retry the
1187failing operation (except by re-entering the the offending piece of
1188code from the top).
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001189
1190When an exception is not handled at all, the interpreter terminates
1191execution of the program, or returns to its interactive main loop.
1192
1193Exceptions are identified by string objects. Two different string
1194objects with the same value identify different exceptions.
1195
1196When an exception is raised, an object (maybe \verb\None\) is passed
1197as the exception's ``parameter''; this object does not affect the
1198selection of an exception handler, but is passed to the selected
1199exception handler as additional information.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001200
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001201See also the description of the \verb\try\ and \verb\raise\
1202statements.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001203
Guido van Rossumf2612d11991-11-21 13:53:03 +00001204\chapter{Expressions and conditions}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001205\index{expression}
1206\index{condition}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001207
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001208{\bf Note:} In this and the following chapters, extended BNF notation
1209will be used to describe syntax, not lexical analysis.
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001210\index{BNF}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001211
1212This chapter explains the meaning of the elements of expressions and
1213conditions. Conditions are a superset of expressions, and a condition
Guido van Rossum670e5a01992-01-17 14:03:20 +00001214may be used wherever an expression is required by enclosing it in
1215parentheses. The only places where expressions are used in the syntax
1216instead of conditions is in expression statements and on the
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001217right-hand side of assignment statements; this catches some nasty bugs
1218like accedentally writing \verb\x == 1\ instead of \verb\x = 1\.
1219\indexii{assignment}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001220
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001221The comma plays several roles in Python's syntax. It is usually an
Guido van Rossum743d1e71992-01-07 16:43:53 +00001222operator with a lower precedence than all others, but occasionally
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001223serves other purposes as well; e.g. it separates function arguments,
Guido van Rossum670e5a01992-01-17 14:03:20 +00001224is used in list and dictionary constructors, and has special semantics
1225in \verb\print\ statements.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001226\index{comma}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001227
1228When (one alternative of) a syntax rule has the form
1229
1230\begin{verbatim}
1231name: othername
1232\end{verbatim}
1233
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001234and no semantics are given, the semantics of this form of \verb\name\
1235are the same as for \verb\othername\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001236\index{syntax}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001237
1238\section{Arithmetic conversions}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001239\indexii{arithmetic}{conversion}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001240
1241When a description of an arithmetic operator below uses the phrase
1242``the numeric arguments are converted to a common type'',
1243this both means that if either argument is not a number, a
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001244\verb\TypeError\ exception is raised, and that otherwise
Guido van Rossumf2612d11991-11-21 13:53:03 +00001245the following conversions are applied:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001246\exindex{TypeError}
1247\indexii{floating point}{number}
1248\indexii{long}{integer}
1249\indexii{plain}{integer}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001250
1251\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001252\item first, if either argument is a floating point number,
Guido van Rossumf2612d11991-11-21 13:53:03 +00001253 the other is converted to floating point;
1254\item else, if either argument is a long integer,
1255 the other is converted to long integer;
Guido van Rossum670e5a01992-01-17 14:03:20 +00001256\item otherwise, both must be plain integers and no conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +00001257 is necessary.
1258\end{itemize}
1259
Guido van Rossumf2612d11991-11-21 13:53:03 +00001260\section{Atoms}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001261\index{atom}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001262
Guido van Rossum670e5a01992-01-17 14:03:20 +00001263Atoms are the most basic elements of expressions. Forms enclosed in
1264reverse quotes or in parentheses, brackets or braces are also
1265categorized syntactically as atoms. The syntax for atoms is:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001266
1267\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001268atom: identifier | literal | enclosure
1269enclosure: parenth_form | list_display | dict_display | string_conversion
Guido van Rossumf2612d11991-11-21 13:53:03 +00001270\end{verbatim}
1271
1272\subsection{Identifiers (Names)}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001273\index{name}
1274\index{identifier}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001275
1276An identifier occurring as an atom is a reference to a local, global
Guido van Rossum670e5a01992-01-17 14:03:20 +00001277or built-in name binding. If a name can be assigned to anywhere in a
1278code block, and is not mentioned in a \verb\global\ statement in that
1279code block, it refers to a local name throughout that code block.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001280Otherwise, it refers to a global name if one exists, else to a
1281built-in name.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001282\indexii{name}{binding}
1283\index{code block}
1284\stindex{global}
1285\indexii{built-in}{name}
1286\indexii{global}{name}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001287
Guido van Rossum670e5a01992-01-17 14:03:20 +00001288When the name is bound to an object, evaluation of the atom yields
1289that object. When a name is not bound, an attempt to evaluate it
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001290raises a \verb\NameError\ exception.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001291\exindex{NameError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001292
1293\subsection{Literals}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001294\index{literal}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001295
Guido van Rossum670e5a01992-01-17 14:03:20 +00001296Python knows string and numeric literals:
1297
1298\begin{verbatim}
1299literal: stringliteral | integer | longinteger | floatnumber
1300\end{verbatim}
1301
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001302Evaluation of a literal yields an object of the given type (string,
1303integer, long integer, floating point number) with the given value.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001304The value may be approximated in the case of floating point literals.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001305See section \ref{literals} for details.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001306
Guido van Rossum670e5a01992-01-17 14:03:20 +00001307All literals correspond to immutable data types, and hence the
1308object's identity is less important than its value. Multiple
1309evaluations of literals with the same value (either the same
1310occurrence in the program text or a different occurrence) may obtain
1311the same object or a different object with the same value.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001312\indexiii{immutable}{data}{type}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001313
1314(In the original implementation, all literals in the same code block
1315with the same type and value yield the same object.)
1316
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001317\subsection{Parenthesized forms}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001318\index{parenthesized form}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001319
Guido van Rossum670e5a01992-01-17 14:03:20 +00001320A parenthesized form is an optional condition list enclosed in
1321parentheses:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001322
Guido van Rossum670e5a01992-01-17 14:03:20 +00001323\begin{verbatim}
1324parenth_form: "(" [condition_list] ")"
1325\end{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001326
Guido van Rossum670e5a01992-01-17 14:03:20 +00001327A parenthesized condition list yields whatever that condition list
1328yields.
1329
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001330An empty pair of parentheses yields an empty tuple object. Since
1331tuples are immutable, the rules for literals apply here.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001332\indexii{empty}{tuple}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001333
1334(Note that tuples are not formed by the parentheses, but rather by use
1335of the comma operator. The exception is the empty tuple, for which
Guido van Rossumb5e1c181992-03-06 10:52:59 +00001336parentheses {\em are} required --- allowing unparenthesized ``nothing''
Guido van Rossum670e5a01992-01-17 14:03:20 +00001337in expressions would causes ambiguities and allow common typos to
1338pass uncaught.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001339\index{comma}
1340\index{tuple}{display}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001341
1342\subsection{List displays}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001343\indexii{list}{display}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001344
Guido van Rossum670e5a01992-01-17 14:03:20 +00001345A list display is a possibly empty series of conditions enclosed in
1346square brackets:
1347
1348\begin{verbatim}
1349list_display: "[" [condition_list] "]"
1350\end{verbatim}
1351
Guido van Rossumf2612d11991-11-21 13:53:03 +00001352A list display yields a new list object.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001353\obindex{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001354
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001355If it has no condition list, the list object has no items. Otherwise,
1356the elements of the condition list are evaluated from left to right
1357and inserted in the list object in that order.
1358\indexii{empty}{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001359
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001360\subsection{Dictionary displays} \label{dict}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001361\indexii{dictionary}{display}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001362
Guido van Rossum670e5a01992-01-17 14:03:20 +00001363A dictionary display is a possibly empty series of key/datum pairs
1364enclosed in curly braces:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001365\index{key}
1366\index{datum}
1367\index{key/datum pair}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001368
1369\begin{verbatim}
1370dict_display: "{" [key_datum_list] "}"
1371key_datum_list: [key_datum ("," key_datum)* [","]
1372key_datum: condition ":" condition
1373\end{verbatim}
1374
Guido van Rossumf2612d11991-11-21 13:53:03 +00001375A dictionary display yields a new dictionary object.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001376\obindex{dictionary}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001377
Guido van Rossum670e5a01992-01-17 14:03:20 +00001378The key/datum pairs are evaluated from left to right to define the
1379entries of the dictionary: each key object is used as a key into the
1380dictionary to store the corresponding datum.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001381
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001382Keys must be strings, otherwise a \verb\TypeError\ exception is
1383raised. Clashes between duplicate keys are not detected; the last
1384datum (textually rightmost in the display) stored for a given key
1385value prevails.
1386\exindex{TypeError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001387
1388\subsection{String conversions}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001389\indexii{string}{conversion}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001390
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001391A string conversion is a condition list enclosed in reverse (or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001392backward) quotes:
1393
1394\begin{verbatim}
1395string_conversion: "`" condition_list "`"
1396\end{verbatim}
1397
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001398A string conversion evaluates the contained condition list and
1399converts the resulting object into a string according to rules
1400specific to its type.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001401
Guido van Rossum4fc43bc1991-11-25 17:26:57 +00001402If the object is a string, a number, \verb\None\, or a tuple, list or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001403dictionary containing only objects whose type is one of these, the
1404resulting string is a valid Python expression which can be passed to
1405the built-in function \verb\eval()\ to yield an expression with the
Guido van Rossumf2612d11991-11-21 13:53:03 +00001406same value (or an approximation, if floating point numbers are
1407involved).
1408
1409(In particular, converting a string adds quotes around it and converts
1410``funny'' characters to escape sequences that are safe to print.)
1411
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001412It is illegal to attempt to convert recursive objects (e.g. lists or
Guido van Rossum670e5a01992-01-17 14:03:20 +00001413dictionaries that contain a reference to themselves, directly or
1414indirectly.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001415\obindex{recursive}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001416
Guido van Rossum60279da1992-04-02 10:24:59 +00001417\section{Primaries} \label{primaries}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001418\index{primary}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001419
1420Primaries represent the most tightly bound operations of the language.
1421Their syntax is:
1422
1423\begin{verbatim}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001424primary: atom | attributeref | subscription | slicing | call
Guido van Rossumf2612d11991-11-21 13:53:03 +00001425\end{verbatim}
1426
1427\subsection{Attribute references}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001428\indexii{attribute}{reference}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001429
Guido van Rossum670e5a01992-01-17 14:03:20 +00001430An attribute reference is a primary followed by a period and a name:
1431
1432\begin{verbatim}
1433attributeref: primary "." identifier
1434\end{verbatim}
1435
1436The primary must evaluate to an object of a type that supports
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001437attribute references, e.g. a module or a list. This object is then
Guido van Rossum670e5a01992-01-17 14:03:20 +00001438asked to produce the attribute whose name is the identifier. If this
1439attribute is not available, the exception \verb\AttributeError\ is
1440raised. Otherwise, the type and value of the object produced is
1441determined by the object. Multiple evaluations of the same attribute
1442reference may yield different objects.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001443\obindex{module}
1444\obindex{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001445
1446\subsection{Subscriptions}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001447\index{subscription}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001448
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001449A subscription selects an item of a sequence (string, tuple or list)
1450or mapping (dictionary) object:
1451\obindex{sequence}
1452\obindex{mapping}
1453\obindex{string}
1454\obindex{tuple}
1455\obindex{list}
1456\obindex{dictionary}
1457\indexii{sequence}{item}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001458
1459\begin{verbatim}
1460subscription: primary "[" condition "]"
1461\end{verbatim}
1462
1463The primary must evaluate to an object of a sequence or mapping type.
1464
1465If it is a mapping, the condition must evaluate to an object whose
1466value is one of the keys of the mapping, and the subscription selects
1467the value in the mapping that corresponds to that key.
1468
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001469If it is a sequence, the condition must evaluate to a plain integer.
1470If this value is negative, the length of the sequence is added to it
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001471(so that, e.g. \verb\x[-1]\ selects the last item of \verb\x\.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001472The resulting value must be a nonnegative integer smaller than the
1473number of items in the sequence, and the subscription selects the item
1474whose index is that value (counting from zero).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001475
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001476A string's items are characters. A character is not a separate data
Guido van Rossum670e5a01992-01-17 14:03:20 +00001477type but a string of exactly one character.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001478\index{character}
1479\indexii{string}{item}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001480
Guido van Rossumf2612d11991-11-21 13:53:03 +00001481\subsection{Slicings}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001482\index{slicing}
1483\index{slice}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001484
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001485A slicing (or slice) selects a range of items in a sequence (string,
1486tuple or list) object:
1487\obindex{sequence}
1488\obindex{string}
1489\obindex{tuple}
1490\obindex{list}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001491
1492\begin{verbatim}
1493slicing: primary "[" [condition] ":" [condition] "]"
1494\end{verbatim}
1495
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001496The primary must evaluate to a sequence object. The lower and upper
1497bound expressions, if present, must evaluate to plain integers;
1498defaults are zero and the sequence's length, respectively. If either
1499bound is negative, the sequence's length is added to it. The slicing
1500now selects all items with index $k$ such that $i <= k < j$ where $i$
1501and $j$ are the specified lower and upper bounds. This may be an
1502empty sequence. It is not an error if $i$ or $j$ lie outside the
1503range of valid indexes (such items don't exist so they aren't
1504selected).
Guido van Rossum670e5a01992-01-17 14:03:20 +00001505
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001506\subsection{Calls} \label{calls}
1507\index{call}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001508
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001509A call calls a callable object (e.g. a function) with a possibly empty
1510series of arguments:
1511\obindex{callable}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001512
1513\begin{verbatim}
1514call: primary "(" [condition_list] ")"
1515\end{verbatim}
1516
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001517The primary must evaluate to a callable object (user-defined
1518functions, built-in functions, methods of built-in objects, class
1519objects, and methods of class instances are callable). If it is a
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001520class, the argument list must be empty; otherwise, the arguments are
1521evaluated.
Guido van Rossum670e5a01992-01-17 14:03:20 +00001522
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001523A call always returns some value, possibly \verb\None\, unless it
1524raises an exception. How this value is computed depends on the type
1525of the callable object. If it is:
1526
1527\begin{description}
1528
1529\item[a user-defined function:] the code block for the function is
1530executed, passing it the argument list. The first thing the code
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001531block will do is bind the formal parameters to the arguments; this is
1532described in section \ref{function}. When the code block executes a
1533\verb\return\ statement, this specifies the return value of the
1534function call.
1535\indexii{function}{call}
1536\indexiii{user-defined}{function}{call}
1537\obindex{user-defined function}
1538\obindex{function}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001539
1540\item[a built-in function or method:] the result is up to the
1541interpreter; see the library reference manual for the descriptions of
1542built-in functions and methods.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001543\indexii{function}{call}
1544\indexii{built-in function}{call}
1545\indexii{method}{call}
1546\indexii{built-in method}{call}
1547\obindex{built-in method}
1548\obindex{built-in function}
1549\obindex{method}
1550\obindex{function}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001551
1552\item[a class object:] a new instance of that class is returned.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001553\obindex{class}
1554\indexii{class object}{call}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001555
1556\item[a class instance method:] the corresponding user-defined
1557function is called, with an argument list that is one longer than the
1558argument list of the call: the instance becomes the first argument.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001559\obindex{class instance}
1560\obindex{instance}
1561\indexii{instance}{call}
1562\indexii{class instance}{call}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00001563
1564\end{description}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001565
Guido van Rossum60279da1992-04-02 10:24:59 +00001566\section{Unary arithmetic operations}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001567\indexiii{unary}{arithmetic}{operation}
1568\indexiii{unary}{bit-wise}{operation}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001569
Guido van Rossum60279da1992-04-02 10:24:59 +00001570All unary arithmetic (and bit-wise) operations have the same priority:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001571
1572\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001573u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001574\end{verbatim}
1575
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001576The unary \verb\"-"\ (minus) operator yields the negation of its
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001577numeric argument.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001578\index{negation}
1579\index{minus}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001580
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001581The unary \verb\"+"\ (plus) operator yields its numeric argument
1582unchanged.
1583\index{plus}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001584
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001585The unary \verb\"~"\ (invert) operator yields the bit-wise inversion
1586of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001587\verb\x\ is defined as \verb\-(x+1)\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001588\index{inversion}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001589
1590In all three cases, if the argument does not have the proper type,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001591a \verb\TypeError\ exception is raised.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001592\exindex{TypeError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001593
Guido van Rossum60279da1992-04-02 10:24:59 +00001594\section{Binary arithmetic operations}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001595\indexiii{binary}{arithmetic}{operation}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001596
Guido van Rossum60279da1992-04-02 10:24:59 +00001597The binary arithmetic operations have the conventional priority
1598levels. Note that some of these operations also apply to certain
1599non-numeric types. There is no ``power'' operator, so there are only
1600two levels, one for multiplicative operators and one for additive
1601operators:
1602
Guido van Rossumf2612d11991-11-21 13:53:03 +00001603\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001604m_expr: u_expr | m_expr "*" u_expr | m_expr "/" u_expr | m_expr "%" u_expr
1605a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001606\end{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001607
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001608The \verb\"*"\ (multiplication) operator yields the product of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001609arguments. The arguments must either both be numbers, or one argument
1610must be a plain integer and the other must be a sequence. In the
1611former case, the numbers are converted to a common type and then
1612multiplied together. In the latter case, sequence repetition is
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001613performed; a negative repetition factor yields an empty sequence.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001614\index{multiplication}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001615
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001616The \verb\"/"\ (division) operator yields the quotient of its
Guido van Rossum670e5a01992-01-17 14:03:20 +00001617arguments. The numeric arguments are first converted to a common
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001618type. Plain or long integer division yields an integer of the same
1619type; the result is that of mathematical division with the `floor'
1620function applied to the result. Division by zero raises the
1621\verb\ZeroDivisionError\ exception.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001622\exindex{ZeroDivisionError}
1623\index{division}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001624
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001625The \verb\"%"\ (modulo) operator yields the remainder from the
Guido van Rossum670e5a01992-01-17 14:03:20 +00001626division of the first argument by the second. The numeric arguments
Guido van Rossum60279da1992-04-02 10:24:59 +00001627are first converted to a common type. A zero right argument raises
1628the \verb\ZeroDivisionError\ exception. The arguments may be floating
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001629point numbers, e.g. \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo
Guido van Rossum60279da1992-04-02 10:24:59 +00001630operator always yields a result with the same sign as its second
1631operand (or zero); the absolute value of the result is strictly
1632smaller than the second operand.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001633\index{modulo}
Guido van Rossum670e5a01992-01-17 14:03:20 +00001634
1635The integer division and modulo operators are connected by the
Guido van Rossum60279da1992-04-02 10:24:59 +00001636following identity: \verb\x == (x/y)*y + (x%y)\. Integer division and
1637modulo are also connected with the built-in function \verb\divmod()\:
1638\verb\divmod(x, y) == (x/y, x%y)\. These identities don't hold for
1639floating point numbers; there a similar identity holds where
1640\verb\x/y\ is replaced by \verb\floor(x/y)\).
Guido van Rossumf2612d11991-11-21 13:53:03 +00001641
Guido van Rossum60279da1992-04-02 10:24:59 +00001642The \verb\"+"\ (addition) operator yields the sum of its arguments.
1643The arguments must either both be numbers, or both sequences of the
1644same type. In the former case, the numbers are converted to a common
1645type and then added together. In the latter case, the sequences are
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001646concatenated.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001647\index{addition}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001648
Guido van Rossum60279da1992-04-02 10:24:59 +00001649The \verb\"-"\ (subtraction) operator yields the difference of its
1650arguments. The numeric arguments are first converted to a common
1651type.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001652\index{subtraction}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001653
Guido van Rossum60279da1992-04-02 10:24:59 +00001654\section{Shifting operations}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001655\indexii{shifting}{operation}
Guido van Rossum60279da1992-04-02 10:24:59 +00001656
1657The shifting operations have lower priority than the arithmetic
1658operations:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001659
1660\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001661shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001662\end{verbatim}
1663
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001664These operators accept plain or long integers as arguments. The
1665arguments are converted to a common type. They shift the first
1666argument to the left or right by the number of bits given by the
1667second argument.
1668
1669A right shift by $n$ bits is defined as division by $2^n$. A left
Guido van Rossum60279da1992-04-02 10:24:59 +00001670shift by $n$ bits is defined as multiplication with $2^n$; for plain
1671integers there is no overflow check so this drops bits and flip the
1672sign if the result is not less than $2^{31}$ in absolute value.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001673
1674Negative shift counts raise a \verb\ValueError\ exception.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001675\exindex{ValueError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001676
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001677\section{Binary bit-wise operations}
1678\indexiii{binary}{bit-wise}{operation}
Guido van Rossum60279da1992-04-02 10:24:59 +00001679
1680Each of the three bitwise operations has a different priority level:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001681
1682\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00001683and_expr: shift_expr | and_expr "&" shift_expr
Guido van Rossum743d1e71992-01-07 16:43:53 +00001684xor_expr: and_expr | xor_expr "^" and_expr
Guido van Rossum743d1e71992-01-07 16:43:53 +00001685or_expr: xor_expr | or_expr "|" xor_expr
Guido van Rossumf2612d11991-11-21 13:53:03 +00001686\end{verbatim}
1687
Guido van Rossum60279da1992-04-02 10:24:59 +00001688The \verb\"&"\ operator yields the bitwise AND of its arguments, which
1689must be plain or long integers. The arguments are converted to a
1690common type.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001691\indexii{bit-wise}{and}
Guido van Rossum60279da1992-04-02 10:24:59 +00001692
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001693The \verb\"^"\ operator yields the bitwise XOR (exclusive OR) of its
Guido van Rossum60279da1992-04-02 10:24:59 +00001694arguments, which must be plain or long integers. The arguments are
1695converted to a common type.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001696\indexii{bit-wise}{xor}
1697\indexii{exclusive}{or}
Guido van Rossum60279da1992-04-02 10:24:59 +00001698
1699The \verb\"|"\ operator yields the bitwise (inclusive) OR of its
1700arguments, which must be plain or long integers. The arguments are
1701converted to a common type.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001702\indexii{bit-wise}{or}
1703\indexii{inclusive}{or}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001704
1705\section{Comparisons}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001706\index{comparison}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001707
Guido van Rossum60279da1992-04-02 10:24:59 +00001708Contrary to C, all comparison operations in Python have the same
1709priority, which is lower than that of any arithmetic, shifting or
1710bitwise operation. Also contrary to C, expressions like
1711\verb\a < b < c\ have the interpretation that is conventional in
1712mathematics:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001713\index{C}
Guido van Rossum60279da1992-04-02 10:24:59 +00001714
Guido van Rossumf2612d11991-11-21 13:53:03 +00001715\begin{verbatim}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001716comparison: or_expr (comp_operator or_expr)*
Guido van Rossum743d1e71992-01-07 16:43:53 +00001717comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
Guido van Rossumf2612d11991-11-21 13:53:03 +00001718\end{verbatim}
1719
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001720Comparisons yield integer values: 1 for true, 0 for false.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001721
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001722Comparisons can be chained arbitrarily, e.g. $x < y <= z$ is
1723equivalent to $x < y$ \verb\and\ $y <= z$, except that $y$ is
1724evaluated only once (but in both cases $z$ is not evaluated at all
1725when $x < y$ is found to be false).
1726\indexii{chaining}{comparisons}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001727
1728Formally, $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 +00001729$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 +00001730$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
1731
1732Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001733between $e_0$ and $e_2$, e.g. $x < y > z$ is perfectly legal.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001734
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001735The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with
1736C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below
1737\verb\<>\ is also implied.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001738
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001739The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
Guido van Rossumf2612d11991-11-21 13:53:03 +00001740the values of two objects. The objects needn't have the same type.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001741If both are numbers, they are coverted to a common type. Otherwise,
1742objects of different types {\em always} compare unequal, and are
1743ordered consistently but arbitrarily.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001744
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001745(This unusual definition of comparison is done to simplify the
1746definition of operations like sorting and the \verb\in\ and \verb\not
1747in\ operators.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001748
1749Comparison of objects of the same type depends on the type:
1750
1751\begin{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001752
1753\item
1754Numbers are compared arithmetically.
1755
1756\item
1757Strings are compared lexicographically using the numeric equivalents
1758(the result of the built-in function \verb\ord\) of their characters.
1759
1760\item
1761Tuples and lists are compared lexicographically using comparison of
1762corresponding items.
1763
1764\item
1765Mappings (dictionaries) are compared through lexicographic
1766comparison of their sorted (key, value) lists.%
1767\footnote{This is expensive since it requires sorting the keys first,
1768but about the only sensible definition. It was tried to compare
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00001769dictionaries by identity only, but this caused surprises because
1770people expected to be able to test a dictionary for emptiness by
1771comparing it to {\tt \{\}}.}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001772
1773\item
1774Most other types compare unequal unless they are the same object;
1775the choice whether one object is considered smaller or larger than
1776another one is made arbitrarily but consistently within one
1777execution of a program.
1778
Guido van Rossumf2612d11991-11-21 13:53:03 +00001779\end{itemize}
1780
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001781The operators \verb\in\ and \verb\not in\ test for sequence
1782membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and
1783only if there exists an index $i$ such that $x = y[i]$.
1784$x ~\verb\not in\~ y$ yields the inverse truth value. The exception
1785\verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is
1786a string and $x$ is not a string of length one.%
1787\footnote{The latter restriction is sometimes a nuisance.}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001788\opindex{in}
1789\opindex{not in}
1790\indexii{membership}{test}
1791\obindex{sequence}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001792
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001793The operators \verb\is\ and \verb\is not\ test for object identity:
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001794$x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same
1795object. $x ~\verb\is not\~ y$ yields the inverse truth value.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001796\opindex{is}
1797\opindex{is not}
1798\indexii{identity}{test}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001799
Guido van Rossum60279da1992-04-02 10:24:59 +00001800\section{Boolean operations} \label{Booleans}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001801\indexii{Boolean}{operation}
Guido van Rossum60279da1992-04-02 10:24:59 +00001802
1803Boolean operations have the lowest priority of all Python operations:
Guido van Rossumf2612d11991-11-21 13:53:03 +00001804
1805\begin{verbatim}
1806condition: or_test
Guido van Rossum743d1e71992-01-07 16:43:53 +00001807or_test: and_test | or_test "or" and_test
1808and_test: not_test | and_test "and" not_test
1809not_test: comparison | "not" not_test
Guido van Rossumf2612d11991-11-21 13:53:03 +00001810\end{verbatim}
1811
Guido van Rossum60279da1992-04-02 10:24:59 +00001812In the context of Boolean operations, and also when conditions are
1813used by control flow statements, the following values are interpreted
1814as false: \verb\None\, numeric zero of all types, empty sequences
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001815(strings, tuples and lists), and empty mappings (dictionaries). All
1816other values are interpreted as true.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001817
1818The operator \verb\not\ yields 1 if its argument is false, 0 otherwise.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001819\opindex{not}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001820
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001821The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false,
Guido van Rossum60279da1992-04-02 10:24:59 +00001822its value is returned; otherwise, $y$ is evaluated and the resulting
1823value is returned.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001824\opindex{and}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001825
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001826The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true,
Guido van Rossum60279da1992-04-02 10:24:59 +00001827its value is returned; otherwise, $y$ is evaluated and the resulting
1828value is returned.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001829\opindex{or}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001830
1831(Note that \verb\and\ and \verb\or\ do not restrict the value and type
1832they return to 0 and 1, but rather return the last evaluated argument.
Guido van Rossum60279da1992-04-02 10:24:59 +00001833This is sometimes useful, e.g. if \verb\s\ is a string that should be
1834replaced by a default value if it is empty, the expression
1835\verb\s or 'foo'\ yields the desired value. Because \verb\not\ has to
1836invent a value anyway, it does not bother to return a value of the
1837same type as its argument, so e.g. \verb\not 'foo'\ yields \verb\0\,
1838not \verb\''\.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001839
1840\section{Expression lists and condition lists}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001841\indexii{expression}{list}
1842\indexii{condition}{list}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001843
1844\begin{verbatim}
1845expr_list: or_expr ("," or_expr)* [","]
1846cond_list: condition ("," condition)* [","]
1847\end{verbatim}
1848
1849The only difference between expression lists and condition lists is
1850the lowest priority of operators that can be used in them without
1851being enclosed in parentheses; condition lists allow all operators,
1852while expression lists don't allow comparisons and Boolean operators
1853(they do allow bitwise and shift operators though).
1854
1855Expression lists are used in expression statements and assignments;
Guido van Rossum60279da1992-04-02 10:24:59 +00001856condition lists are used everywhere else where a list of
1857comma-separated values is required.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001858
1859An expression (condition) list containing at least one comma yields a
1860tuple. The length of the tuple is the number of expressions
1861(conditions) in the list. The expressions (conditions) are evaluated
Guido van Rossum60279da1992-04-02 10:24:59 +00001862from left to right. (Conditions lists are used syntactically is a few
1863places where no tuple is constructed but a list of values is needed
1864nevertheless.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001865\obindex{tuple}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001866
1867The trailing comma is required only to create a single tuple (a.k.a. a
1868{\em singleton}); it is optional in all other cases. A single
1869expression (condition) without a trailing comma doesn't create a
1870tuple, but rather yields the value of that expression (condition).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001871\indexii{trailing}{comma}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001872
Guido van Rossum60279da1992-04-02 10:24:59 +00001873(To create an empty tuple, use an empty pair of parentheses:
1874\verb\()\.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00001875
1876\chapter{Simple statements}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001877\indexii{simple}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001878
1879Simple statements are comprised within a single logical line.
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001880Several simple statements may occur on a single line separated
Guido van Rossumf2612d11991-11-21 13:53:03 +00001881by semicolons. The syntax for simple statements is:
1882
1883\begin{verbatim}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001884simple_stmt: expression_stmt
Guido van Rossum60279da1992-04-02 10:24:59 +00001885 | assignment_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001886 | pass_stmt
1887 | del_stmt
1888 | print_stmt
1889 | return_stmt
1890 | raise_stmt
1891 | break_stmt
1892 | continue_stmt
1893 | import_stmt
Guido van Rossum743d1e71992-01-07 16:43:53 +00001894 | global_stmt
Guido van Rossumf2612d11991-11-21 13:53:03 +00001895\end{verbatim}
1896
1897\section{Expression statements}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001898\indexii{expression}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001899
Guido van Rossum60279da1992-04-02 10:24:59 +00001900Expression statements are used (mostly interactively) to compute and
1901write a value, or (usually) to call a procedure (a function that
1902returns no meaningful result; in Python, procedures return the value
1903\verb\None\):
1904
Guido van Rossumf2612d11991-11-21 13:53:03 +00001905\begin{verbatim}
1906expression_stmt: expression_list
1907\end{verbatim}
1908
Guido van Rossum60279da1992-04-02 10:24:59 +00001909An expression statement evaluates the expression list (which may be a
1910single expression). If the value is not \verb\None\, it is converted
1911to a string using the rules for string conversions (expressions in
1912reverse quotes), and the resulting string is written to standard
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001913output (see section \ref{print}) on a line by itself.
1914\indexii{expression}{list}
1915\ttindex{None}
1916\indexii{string}{conversion}
1917\index{output}
1918\indexii{standard}{output}
1919\indexii{writing}{values}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001920
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001921(The exception for \verb\None\ is made so that procedure calls, which
1922are syntactically equivalent to expressions, do not cause any output.
1923A tuple with only \verb\None\ items is written normally.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001924\indexii{procedure}{call}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001925
Guido van Rossum60279da1992-04-02 10:24:59 +00001926\section{Assignment statements}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001927\indexii{assignment}{statement}
Guido van Rossum60279da1992-04-02 10:24:59 +00001928
1929Assignment statements are used to (re)bind names to values and to
1930modify attributes or items of mutable objects:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001931\indexii{binding}{name}
1932\indexii{rebinding}{name}
1933\obindex{mutable}
1934\indexii{attribute}{assignment}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001935
1936\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00001937assignment_stmt: (target_list "=")+ expression_list
1938target_list: target ("," target)* [","]
1939target: identifier | "(" target_list ")" | "[" target_list "]"
1940 | attributeref | subscription | slicing
Guido van Rossumf2612d11991-11-21 13:53:03 +00001941\end{verbatim}
1942
Guido van Rossum60279da1992-04-02 10:24:59 +00001943(See section \ref{primaries} for the syntax definitions for the last
Guido van Rossumf2612d11991-11-21 13:53:03 +00001944three symbols.)
1945
Guido van Rossum60279da1992-04-02 10:24:59 +00001946An assignment statement evaluates the expression list (remember that
1947this can be a single expression or a comma-separated list, the latter
1948yielding a tuple) and assigns the single resulting object to each of
1949the target lists, from left to right.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001950\indexii{expression}{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001951
Guido van Rossum60279da1992-04-02 10:24:59 +00001952Assignment is defined recursively depending on the form of the target
1953(list). When a target is part of a mutable object (an attribute
1954reference, subscription or slicing), the mutable object must
1955ultimately perform the assignment and decide about its validity, and
1956may raise an exception if the assignment is unacceptable. The rules
1957observed by various types and the exceptions raised are given with the
1958definition of the object types (see section \ref{types}).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001959\index{target}
1960\indexii{target}{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001961
Guido van Rossum60279da1992-04-02 10:24:59 +00001962Assignment of an object to a target list is recursively defined as
1963follows.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001964\indexiii{target}{list}{assignment}
Guido van Rossumf2612d11991-11-21 13:53:03 +00001965
1966\begin{itemize}
1967\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001968If the target list is a single target: the object is assigned to that
1969target.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001970
1971\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001972If the target list is a comma-separated list of targets: the object
1973must be a tuple with the same number of items as the list contains
1974targets, and the items are assigned, from left to right, to the
1975corresponding targets.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001976
1977\end{itemize}
1978
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001979Assignment of an object to a single target is recursively defined as
Guido van Rossum60279da1992-04-02 10:24:59 +00001980follows.
Guido van Rossumf2612d11991-11-21 13:53:03 +00001981
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001982\begin{itemize} % nested
Guido van Rossumf2612d11991-11-21 13:53:03 +00001983
1984\item
1985If the target is an identifier (name):
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001986
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001987\begin{itemize}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001988
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001989\item
1990If the name does not occur in a \verb\global\ statement in the current
Guido van Rossum60279da1992-04-02 10:24:59 +00001991code block: the name is bound to the object in the current local name
1992space.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001993\stindex{global}
1994
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001995\item
Guido van Rossum60279da1992-04-02 10:24:59 +00001996Otherwise: the name is bound to the object in the current global name
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00001997space.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00001998
1999\end{itemize} % nested
2000
Guido van Rossum60279da1992-04-02 10:24:59 +00002001The name is rebound if it was already bound.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002002
2003\item
Guido van Rossum60279da1992-04-02 10:24:59 +00002004If the target is a target list enclosed in parentheses: the object is
2005assigned to that target list as described above.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002006
2007\item
Guido van Rossum60279da1992-04-02 10:24:59 +00002008If the target is a target list enclosed in square brackets: the object
2009must be a list with the same number of items as the target list
2010contains targets, and its items are assigned, from left to right, to
2011the corresponding targets.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002012
2013\item
Guido van Rossum60279da1992-04-02 10:24:59 +00002014If the target is an attribute reference: The primary expression in the
2015reference is evaluated. It should yield an object with assignable
2016attributes; if this is not the case, \verb\TypeError\ is raised. That
2017object is then asked to assign the assigned object to the given
2018attribute; if it cannot perform the assignment, it raises an exception
2019(usually but not necessarily \verb\AttributeError\).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002020\indexii{attribute}{assignment}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002021
2022\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002023If the target is a subscription: The primary expression in the
2024reference is evaluated. It should yield either a mutable sequence
2025(list) object or a mapping (dictionary) object. Next, the subscript
2026expression is evaluated.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002027\indexii{subscription}{assignment}
2028\obindex{mutable}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002029
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002030If the primary is a mutable sequence object (a list), the subscript
2031must yield a plain integer. If it is negative, the sequence's length
2032is added to it. The resulting value must be a nonnegative integer
2033less than the sequence's length, and the sequence is asked to assign
2034the assigned object to its item with that index. If the index is out
2035of range, \verb\IndexError\ is raised (assignment to a subscripted
2036sequence cannot add new items to a list).
2037\obindex{sequence}
2038\obindex{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002039
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002040If the primary is a mapping (dictionary) object, the subscript must
2041have a type compatible with the mapping's key type, and the mapping is
2042then asked to to create a key/datum pair which maps the subscript to
2043the assigned object. This can either replace an existing key/value
2044pair with the same key value, or insert a new key/value pair (if no
2045key with the same value existed).
2046\obindex{mapping}
2047\obindex{dictionary}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002048
2049\item
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002050If the target is a slicing: The primary expression in the reference is
2051evaluated. It should yield a mutable sequence (list) object. The
2052assigned object should be a sequence object of the same type. Next,
2053the lower and upper bound expressions are evaluated, insofar they are
2054present; defaults are zero and the sequence's length. The bounds
2055should evaluate to (small) integers. If either bound is negative, the
2056sequence's length is added to it. The resulting bounds are clipped to
2057lie between zero and the sequence's length, inclusive. Finally, the
2058sequence object is asked to replace the items indicated by the slice
2059with the items of the assigned sequence. This may change the
2060sequence's length, if it allows it.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002061\indexii{slicing}{assignment}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002062
2063\end{itemize}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002064
Guido van Rossumf2612d11991-11-21 13:53:03 +00002065(In the original implementation, the syntax for targets is taken
2066to be the same as for expressions, and invalid syntax is rejected
2067during the code generation phase, causing less detailed error
2068messages.)
2069
Guido van Rossum68c172e1992-01-21 11:34:56 +00002070\section{The {\tt pass} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002071\stindex{pass}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002072
2073\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002074pass_stmt: "pass"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002075\end{verbatim}
2076
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002077\verb\pass\ is a null operation --- when it is executed, nothing
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002078happens. It is useful as a placeholder when a statement is
2079required syntactically, but no code needs to be executed, for example:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002080\indexii{null}{operation}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002081
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002082\begin{verbatim}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002083def f(arg): pass # a function that does nothing (yet)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002084
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002085class C: pass # an class with no methods (yet)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002086\end{verbatim}
2087
Guido van Rossum68c172e1992-01-21 11:34:56 +00002088\section{The {\tt del} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002089\stindex{del}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002090
2091\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002092del_stmt: "del" target_list
Guido van Rossumf2612d11991-11-21 13:53:03 +00002093\end{verbatim}
2094
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002095Deletion is recursively defined very similar to the way assignment is
2096defined. Rather that spelling it out in full details, here are some
2097hints.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002098\indexii{deletion}{target}
2099\indexiii{deletion}{target}{list}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002100
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002101Deletion of a target list recursively deletes each target, from left
2102to right.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002103
2104Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002105from the local or global name space, depending on whether the name
2106occurs in a \verb\global\ statement in the same code block.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002107\stindex{global}
2108\indexii{unbinding}{name}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002109
2110Deletion of attribute references, subscriptions and slicings
2111is passed to the primary object involved; deletion of a slicing
2112is in general equivalent to assignment of an empty slice of the
2113right type (but even this is determined by the sliced object).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002114\indexii{attribute}{deletion}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002115
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002116\section{The {\tt print} statement} \label{print}
2117\stindex{print}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002118
2119\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002120print_stmt: "print" [ condition ("," condition)* [","] ]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002121\end{verbatim}
2122
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002123\verb\print\ evaluates each condition in turn and writes the resulting
2124object to standard output (see below). If an object is not a string,
2125it is first converted to a string using the rules for string
2126conversions. The (resulting or original) string is then written. A
2127space is written before each object is (converted and) written, unless
2128the output system believes it is positioned at the beginning of a
2129line. This is the case: (1) when no characters have yet been written
2130to standard output; or (2) when the last character written to standard
2131output is \verb/\n/; or (3) when the last write operation on standard
2132output was not a \verb\print\ statement. (In some cases it may be
2133functional to write an empty string to standard output for this
2134reason.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002135\index{output}
2136\indexii{writing}{values}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002137
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002138A \verb/"\n"/ character is written at the end, unless the \verb\print\
2139statement ends with a comma. This is the only action if the statement
2140contains just the keyword \verb\print\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002141\indexii{trailing}{comma}
2142\indexii{newline}{suppression}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002143
2144Standard output is defined as the file object named \verb\stdout\
2145in the built-in module \verb\sys\. If no such object exists,
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002146or if it is not a writable file, a \verb\RuntimeError\ exception is raised.
Guido van Rossumf2612d11991-11-21 13:53:03 +00002147(The original implementation attempts to write to the system's original
2148standard output instead, but this is not safe, and should be fixed.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002149\indexii{standard}{output}
2150\bimodindex{sys}
2151\ttindex{stdout}
2152\exindex{RuntimeError}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002153
Guido van Rossum68c172e1992-01-21 11:34:56 +00002154\section{The {\tt return} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002155\stindex{return}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002156
2157\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002158return_stmt: "return" [condition_list]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002159\end{verbatim}
2160
2161\verb\return\ may only occur syntactically nested in a function
2162definition, not within a nested class definition.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002163\indexii{function}{definition}
2164\indexii{class}{definition}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002165
2166If a condition list is present, it is evaluated, else \verb\None\
2167is substituted.
2168
2169\verb\return\ leaves the current function call with the condition
2170list (or \verb\None\) as return value.
2171
2172When \verb\return\ passes control out of a \verb\try\ statement
2173with a \verb\finally\ clause, that finally clause is executed
2174before really leaving the function.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002175\kwindex{finally}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002176
Guido van Rossum68c172e1992-01-21 11:34:56 +00002177\section{The {\tt raise} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002178\stindex{raise}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002179
2180\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002181raise_stmt: "raise" condition ["," condition]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002182\end{verbatim}
2183
2184\verb\raise\ evaluates its first condition, which must yield
2185a string object. If there is a second condition, this is evaluated,
2186else \verb\None\ is substituted.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002187\index{exception}
2188\indexii{raising}{exception}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002189
2190It then raises the exception identified by the first object,
2191with the second one (or \verb\None\) as its parameter.
2192
Guido van Rossum68c172e1992-01-21 11:34:56 +00002193\section{The {\tt break} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002194\stindex{break}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002195
2196\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002197break_stmt: "break"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002198\end{verbatim}
2199
2200\verb\break\ may only occur syntactically nested in a \verb\for\
2201or \verb\while\ loop, not nested in a function or class definition.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002202\stindex{for}
2203\stindex{while}
2204\indexii{loop}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002205
2206It terminates the neares enclosing loop, skipping the optional
2207\verb\else\ clause if the loop has one.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002208\kwindex{else}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002209
2210If a \verb\for\ loop is terminated by \verb\break\, the loop control
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002211target keeps its current value.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002212\indexii{loop control}{target}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002213
2214When \verb\break\ passes control out of a \verb\try\ statement
2215with a \verb\finally\ clause, that finally clause is executed
2216before really leaving the loop.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002217\kwindex{finally}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002218
Guido van Rossum68c172e1992-01-21 11:34:56 +00002219\section{The {\tt continue} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002220\stindex{continue}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002221
2222\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002223continue_stmt: "continue"
Guido van Rossumf2612d11991-11-21 13:53:03 +00002224\end{verbatim}
2225
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002226\verb\continue\ may only occur syntactically nested in a \verb\for\ or
2227\verb\while\ loop, not nested in a function or class definition, and
2228not nested in the \verb\try\ clause of a \verb\try\ statement with a
2229\verb\finally\ clause (it may occur nested in a \verb\except\ or
2230\verb\finally\ clause of a \verb\try\ statement though).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002231\stindex{for}
2232\stindex{while}
2233\indexii{loop}{statement}
2234\kwindex{finally}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002235
2236It continues with the next cycle of the nearest enclosing loop.
2237
Guido van Rossum862c6f11992-01-29 14:47:05 +00002238\section{The {\tt import} statement} \label{import}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002239\stindex{import}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002240
2241\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002242import_stmt: "import" identifier ("," identifier)*
2243 | "from" identifier "import" identifier ("," identifier)*
2244 | "from" identifier "import" "*"
2245\end{verbatim}
2246
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002247Import statements are executed in two steps: (1) find a module, and
2248initialize it if necessary; (2) define a name or names in the local
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002249name space (of the scope where the \verb\import\ statement occurs).
2250The first form (without \verb\from\) repeats these steps for each
2251identifier in the list, the \verb\from\ form performs them once, with
2252the first identifier specifying the module name.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002253\indexii{importing}{module}
2254\indexii{name}{binding}
2255\kwindex{from}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002256
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002257The system maintains a table of modules that have been initialized,
2258indexed by module name. (The current implementation makes this table
2259accessible as \verb\sys.modules\.) When a module name is found in
2260this table, step (1) is finished. If not, a search for a module
2261definition is started. This first looks for a built-in module
2262definition, and if no built-in module if the given name is found, it
2263searches a user-specified list of directories for a file whose name is
2264the module name with extension \verb\".py"\. (The current
2265implementation uses the list of strings \verb\sys.path\ as the search
2266path; it is initialized from the shell environment variable
2267\verb\$PYTHONPATH\, with an installation-dependent default.)
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002268\ttindex{modules}
2269\ttindex{sys.modules}
2270\indexii{module}{name}
2271\indexii{built-in}{module}
2272\indexii{user-defined}{module}
2273\bimodindex{sys}
2274\ttindex{path}
2275\ttindex{sys.path}
2276\indexii{filename}{extension}
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002277
2278If a built-in module is found, its built-in initialization code is
2279executed and step (1) is finished. If no matching file is found,
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002280\verb\ImportError\ is raised. If a file is found, it is parsed,
2281yielding an executable code block. If a syntax error occurs,
2282\verb\SyntaxError\ is raised. Otherwise, an empty module of the given
2283name is created and inserted in the module table, and then the code
2284block is executed in the context of this module. Exceptions during
2285this execution terminate step (1).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002286\indexii{module}{initialization}
2287\exindex{SyntaxError}
2288\exindex{ImportError}
2289\index{code block}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002290
2291When step (1) finishes without raising an exception, step (2) can
2292begin.
2293
2294The first form of \verb\import\ statement binds the module name in the
2295local name space to the module object, and then goes on to import the
2296next identifier, if any. The \verb\from\ from does not bind the
2297module name: it goes through the list of identifiers, looks each one
2298of them up in the module found in step (1), and binds the name in the
2299local name space to the object thus found. If a name is not found,
2300\verb\ImportError\ is raised. If the list of identifiers is replaced
2301by a star (\verb\*\), all names defined in the module are bound,
2302except those beginning with an underscore(\verb\_\).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002303\indexii{name}{binding}
2304\exindex{ImportError}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002305
2306Names bound by import statements may not occur in \verb\global\
2307statements in the same scope.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002308\stindex{global}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002309
2310The \verb\from\ form with \verb\*\ may only occur in a module scope.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002311\kwindex{from}
2312\ttindex{from ... import *}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002313
2314(The current implementation does not enforce the latter two
2315restrictions, but programs should not abuse this freedom, as future
2316implementations may enforce them or silently change the meaning of the
2317program.)
Guido van Rossum0f1f9da1992-01-20 17:10:21 +00002318
Guido van Rossum862c6f11992-01-29 14:47:05 +00002319\section{The {\tt global} statement} \label{global}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002320\stindex{global}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002321
2322\begin{verbatim}
2323global_stmt: "global" identifier ("," identifier)*
Guido van Rossumf2612d11991-11-21 13:53:03 +00002324\end{verbatim}
2325
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002326The \verb\global\ statement is a declaration which holds for the
2327entire current scope. It means that the listed identifiers are to be
2328interpreted as globals. While {\em using} global names is automatic
2329if they are not defined in the local scope, {\em assigning} to global
2330names would be impossible without \verb\global\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002331\indexiii{global}{name}{binding}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002332
2333Names listed in a \verb\global\ statement must not be used in the same
2334scope before that \verb\global\ statement is executed.
2335
2336Name listed in a \verb\global\ statement must not be defined as formal
2337parameters or in a \verb\for\ loop control target, \verb\class\
2338definition, function definition, or \verb\import\ statement.
2339
2340(The current implementation does not enforce the latter two
2341restrictions, but programs should not abuse this freedom, as future
2342implementations may enforce them or silently change the meaning of the
2343program.)
Guido van Rossumf2612d11991-11-21 13:53:03 +00002344
2345\chapter{Compound statements}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002346\indexii{compound}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002347
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002348Compound statements contain (groups of) other statements; they affect
Guido van Rossum60279da1992-04-02 10:24:59 +00002349or control the execution of those other statements in some way. In
2350general, compound statements span multiple lines, although in simple
2351incarnations a whole compound statement may be contained in one line.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002352
2353The \verb\if\, \verb\while\ and \verb\for\ statements implement
2354traditional control flow constructs. \verb\try\ specifies exception
2355handlers and/or cleanup code for a group of statements. Function and
2356class definitions are also syntactically compound statements.
2357
2358Compound statements consist of one or more `clauses'. A clause
2359consists of a header and a `suite'. The clause headers of a
Guido van Rossum60279da1992-04-02 10:24:59 +00002360particular compound statement are all at the same indentation level.
2361Each clause header begins with a uniquely identifying keyword and ends
2362with a colon. A suite is a group of statements controlled by a
2363clause. A suite can be one or more semicolon-separated simple
2364statements on the same line as the header, following the header's
2365colon, or it can be one or more indented statements on subsequent
2366lines. Only the latter form of suite can contain nested compound
2367statements; the following is illegal, mostly because it wouldn't be
2368clear to which \verb\if\ clause a following \verb\else\ clause would
2369belong:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002370\index{clause}
2371\index{suite}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002372
2373\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002374if test1: if test2: print x
Guido van Rossumf2612d11991-11-21 13:53:03 +00002375\end{verbatim}
2376
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002377Also note that the semicolon binds tighter that the colon in this
Guido van Rossum60279da1992-04-02 10:24:59 +00002378context, so that in the following example, either all or none of the
2379\verb\print\ statements are executed:
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002380
2381\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00002382if x < y < z: print x; print y; print z
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002383\end{verbatim}
2384
2385Summarizing:
2386
2387\begin{verbatim}
2388compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
2389suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
2390statement: stmt_list NEWLINE | compound_stmt
2391stmt_list: simple_stmt (";" simple_stmt)* [";"]
2392\end{verbatim}
2393
2394Note that statements always ends in a \verb\NEWLINE\ possibly followed
2395by a \verb\DEDENT\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002396\index{NEWLINE token}
2397\index{DEDENT token}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002398
2399Also note that optional continuation clauses always begin with a
2400keyword that cannot start a statement, thus there are no ambiguities
2401(the `dangling \verb\else\' problem is solved in Python by requiring
2402nested \verb\if\ statements to be indented).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002403\indexii{dangling}{else}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002404
Guido van Rossum60279da1992-04-02 10:24:59 +00002405The formatting of the grammar rules in the following sections places
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002406each clause on a separate line for clarity.
2407
Guido van Rossum68c172e1992-01-21 11:34:56 +00002408\section{The {\tt if} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002409\stindex{if}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002410
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002411The \verb\if\ statement is used for conditional execution:
2412
Guido van Rossumf2612d11991-11-21 13:53:03 +00002413\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002414if_stmt: "if" condition ":" suite
2415 ("elif" condition ":" suite)*
2416 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002417\end{verbatim}
2418
Guido van Rossum60279da1992-04-02 10:24:59 +00002419It selects exactly one of the suites by evaluating the conditions one
2420by one until one is found to be true (see section \ref{Booleans} for
2421the definition of true and false); then that suite is executed (and no
2422other part of the \verb\if\ statement is executed or evaluated). If
2423all conditions are false, the suite of the \verb\else\ clause, if
2424present, is executed.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002425\kwindex{elif}
2426\kwindex{else}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002427
Guido van Rossum68c172e1992-01-21 11:34:56 +00002428\section{The {\tt while} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002429\stindex{while}
2430\indexii{loop}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002431
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002432The \verb\while\ statement is used for repeated execution as long as a
2433condition is true:
2434
Guido van Rossumf2612d11991-11-21 13:53:03 +00002435\begin{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002436while_stmt: "while" condition ":" suite
2437 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002438\end{verbatim}
2439
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002440This repeatedly tests the condition and, if it is true, executes the
2441first suite; if the condition is false (which may be the first time it
Guido van Rossum60279da1992-04-02 10:24:59 +00002442is tested) the suite of the \verb\else\ clause, if present, is
2443executed and the loop terminates.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002444\kwindex{else}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002445
2446A \verb\break\ statement executed in the first suite terminates the
2447loop without executing the \verb\else\ clause's suite. A
2448\verb\continue\ statement executed in the first suited skips the rest
2449of the suite and goes back to testing the condition.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002450\stindex{break}
2451\stindex{continue}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002452
Guido van Rossum68c172e1992-01-21 11:34:56 +00002453\section{The {\tt for} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002454\stindex{for}
2455\indexii{loop}{statement}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002456
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002457The \verb\for\ statement is used to iterate over the elements of a
2458sequence (string, tuple or list):
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002459\obindex{sequence}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002460
Guido van Rossumf2612d11991-11-21 13:53:03 +00002461\begin{verbatim}
Guido van Rossum743d1e71992-01-07 16:43:53 +00002462for_stmt: "for" target_list "in" condition_list ":" suite
2463 ["else" ":" suite]
Guido van Rossumf2612d11991-11-21 13:53:03 +00002464\end{verbatim}
2465
Guido van Rossum60279da1992-04-02 10:24:59 +00002466The condition list is evaluated once; it should yield a sequence. The
2467suite is then executed once for each item in the sequence, in the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002468order of ascending indices. Each item in turn is assigned to the
2469target list using the standard rules for assignments, and then the
Guido van Rossum60279da1992-04-02 10:24:59 +00002470suite is executed. When the items are exhausted (which is immediately
2471when the sequence is empty), the suite in the \verb\else\ clause, if
2472present, is executed, and the loop terminates.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002473\kwindex{in}
2474\kwindex{else}
2475\indexii{target}{list}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002476
2477A \verb\break\ statement executed in the first suite terminates the
2478loop without executing the \verb\else\ clause's suite. A
2479\verb\continue\ statement executed in the first suited skips the rest
Guido van Rossum60279da1992-04-02 10:24:59 +00002480of the suite and continues with the next item, or with the \verb\else\
2481clause if there was no next item.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002482\stindex{break}
2483\stindex{continue}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002484
2485The suite may assign to the variable(s) in the target list; this does
2486not affect the next item assigned to it.
2487
Guido van Rossum60279da1992-04-02 10:24:59 +00002488The target list is not deleted when the loop is finished, but if the
2489sequence is empty, it will not have been assigned to at all by the
2490loop.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002491
Guido van Rossum60279da1992-04-02 10:24:59 +00002492Hint: the built-in function \verb\range()\ returns a sequence of
2493integers suitable to emulate the effect of Pascal's \verb\for i := a
2494to b do\; e.g. \verb\range(3)\ returns the list \verb\[0, 1, 2]\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002495\bifuncindex{range}
2496\index{Pascal}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002497
2498{\bf Warning:} There is a subtlety when the sequence is being modified
Guido van Rossum60279da1992-04-02 10:24:59 +00002499by the loop (this can only occur for mutable sequences, i.e. lists).
2500An internal counter is used to keep track of which item is used next,
2501and this is incremented on each iteration. When this counter has
2502reached the length of the sequence the loop terminates. This means that
2503if the suite deletes the current (or a previous) item from the
2504sequence, the next item will be skipped (since it gets the index of
2505the current item which has already been treated). Likewise, if the
2506suite inserts an item in the sequence before the current item, the
2507current item will be treated again the next time through the loop.
2508This can lead to nasty bugs that can be avoided by making a temporary
2509copy using a slice of the whole sequence, e.g.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002510\index{loop!over mutable sequence}
2511\index{mutable sequence!loop over}
Guido van Rossum60279da1992-04-02 10:24:59 +00002512
2513\begin{verbatim}
2514for x in a[:]:
2515 if x < 0: a.remove(x)
2516\end{verbatim}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002517
Guido van Rossum68c172e1992-01-21 11:34:56 +00002518\section{The {\tt try} statement}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002519\stindex{try}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002520
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002521The \verb\try\ statement specifies exception handlers and/or cleanup
2522code for a group of statements:
2523
Guido van Rossumf2612d11991-11-21 13:53:03 +00002524\begin{verbatim}
Guido van Rossum60279da1992-04-02 10:24:59 +00002525try_stmt: try_exc_stmt | try_fin_stmt
2526try_exc_stmt: "try" ":" suite
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002527 ("except" [condition ["," target]] ":" suite)+
Guido van Rossum60279da1992-04-02 10:24:59 +00002528try_fin_stmt: "try" ":" suite
2529 "finally" ":" suite
Guido van Rossumf2612d11991-11-21 13:53:03 +00002530\end{verbatim}
2531
Guido van Rossum60279da1992-04-02 10:24:59 +00002532There are two forms of \verb\try\ statement: \verb\try...except\ and
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002533\verb\try...finally\. These forms cannot be mixed.
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002534
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002535The \verb\try...except\ form specifies one or more exception handlers
2536(the \verb\except\ clauses). When no exception occurs in the
2537\verb\try\ clause, no exception handler is executed. When an
2538exception occurs in the \verb\try\ suite, a search for an exception
2539handler is started. This inspects the except clauses in turn until
2540one is found that matches the exception. A condition-less except
2541clause, if present, must be last; it matches any exception. For an
2542except clause with a condition, that condition is evaluated, and the
2543clause matches the exception if the resulting object is ``compatible''
2544with the exception. An object is compatible with an exception if it
2545is either the object that identifies the exception or it is a tuple
2546containing an item that is compatible with the exception. Note that
2547the object identities must match, i.e. it must be the same object, not
2548just an onject with the same value.
2549\kwindex{except}
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002550
2551If no except clause matches the exception, the search for an exception
2552handler continues in the surrounding code and on the invocation stack.
2553
2554If the evaluation of a condition in the header of an except clause
2555raises an exception, the original search for a handler is cancelled
2556and a search starts for the new exception in the surrounding code and
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002557on the call stack (it is treated as if the entire \verb\try\ statement
2558raised the exception).
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002559
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002560When a matching except clause is found, the exception's parameter is
2561assigned to the target specified in that except clause, if present,
2562and the except clause's suite is executed. When the end of this suite
2563is reached, execution continues normally after the entire try
2564statement. (This means that if two nested handlers exist for the same
2565exception, and the exception occurs in the try clause of the inner
2566handler, the outer handler will not handle the exception.)
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002567
2568The \verb\try...finally\ form specifies a `cleanup' handler. The
2569\verb\try\ clause is executed. When no exception occurs, the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002570\verb\finally\ clause is executed. When an exception occurs in the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002571\verb\try\ clause, the exception is temporarily saved, the
2572\verb\finally\ clause is executed, and then the saved exception is
2573re-raised. If the \verb\finally\ clause raises another exception or
2574executes a \verb\return\, \verb\break\ or \verb\continue\ statement,
2575the saved exception is lost.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002576\kwindex{finally}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002577
2578When a \verb\return\ or \verb\break\ statement is executed in the
Guido van Rossumcf8148b1992-03-02 16:13:50 +00002579\verb\try\ suite of a \verb\try...finally\ statement, the
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002580\verb\finally\ clause is also executed `on the way out'. A
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002581\verb\continue\ statement is illegal in the \verb\try\ clause. (The
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002582reason is a problem with the current implementation --- this
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002583restriction may be lifted in the future).
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002584\stindex{return}
2585\stindex{break}
2586\stindex{continue}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002587
Guido van Rossum862c6f11992-01-29 14:47:05 +00002588\section{Function definitions} \label{function}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002589\indexii{function}{definition}
Guido van Rossum255ad6e1992-01-28 18:10:46 +00002590
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002591A function definition defines a user-defined function object (see
2592section \ref{types}):
2593\obindex{user-defined function}
2594\obindex{function}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002595
2596\begin{verbatim}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002597funcdef: "def" funcname "(" [parameter_list] ")" ":" suite
2598parameter_list: (parameter ",")* ("*" identifier | parameter [","])
2599sublist: parameter ("," parameter)* [","]
2600parameter: identifier | "(" sublist ")"
2601funcname: identifier
Guido van Rossumf2612d11991-11-21 13:53:03 +00002602\end{verbatim}
2603
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002604A function definition is an executable statement. Its execution binds
2605the function name in the current local name space to a function object
2606(a wrapper around the executable code for the function). This
2607function object contains a reference to the current global name space
2608as the global name space to be used when the function is called.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002609\indexii{function}{name}
2610\indexii{name}{binding}
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002611
2612The function definition does not execute the function body; this gets
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002613executed only when the function is called.
2614
2615Function call semantics are described in section \ref{calls}. When a
2616user-defined function is called, the arguments (a.k.a. actual
2617parameters) are bound to the (formal) parameters, as follows:
2618\indexii{function}{call}
2619\indexiii{user-defined}{function}{call}
2620\index{parameter}
2621\index{argument}
2622\indexii{parameter}{formal}
2623\indexii{parameter}{actual}
2624
2625\begin{itemize}
2626
2627\item
2628If there are no formal parameters, there must be no arguments.
2629
2630\item
2631If the formal parameter list does not end in a star followed by an
2632identifier, there must be exactly as many arguments as there are
2633parameters in the formal parameter list (at the top level); the
2634arguments are assigned to the formal parameters one by one. Note that
2635the presence or absence of a trailing comma at the top level in either
2636the formal or the actual parameter list makes no difference. The
2637assignment to a formal parameter is performed as if the parameter
2638occurs on the left hand side of an assignment statement whose right
2639hand side's value is that of the argument.
2640
2641\item
2642If the formal parameter list ends in a star followed by an identifier,
2643preceded by zero or more comma-followed parameters, there must be at
2644least as many arguments as there are parameters preceding the star.
2645Call this number {\em N}. The first {\em N} arguments are assigned to
2646the corresponding formal parameters in the way descibed above. A
2647tuple containing the remaining arguments, if any, is then assigned to
2648the identifier following the star. This variable will always be a
2649tuple: if there are no extra arguments, its value is \verb\()\, if
2650there is just one extra argument, it is a singleton tuple.
2651\indexii{variable length}{parameter list}
2652
2653\end{itemize}
2654
2655Note that the `variable length parameter list' feature only works at
2656the top level of the parameter list; individual parameters use a model
2657corresponding more closely to that of ordinary assignment. While the
2658latter model is generally preferable, because of the greater type
2659safety it offers (wrong-sized tuples aren't silently mistreated),
2660variable length parameter lists are a sufficiently accepted practice
2661in most programming languages that a compromise has been worked out.
2662(And anyway, assignment has no equivalent for empty argument lists.)
Guido van Rossum862c6f11992-01-29 14:47:05 +00002663
2664\section{Class definitions} \label{class}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002665\indexii{class}{definition}
Guido van Rossum862c6f11992-01-29 14:47:05 +00002666
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002667A class definition defines a class object (see section \ref{types}):
2668\obindex{class}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002669
2670\begin{verbatim}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002671classdef: "class" classname [inheritance] ":" suite
2672inheritance: "(" [condition_list] ")"
2673classname: identifier
Guido van Rossumf2612d11991-11-21 13:53:03 +00002674\end{verbatim}
2675
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002676A class definition is an executable statement. It first evaluates the
2677inheritance list, if present. Each item in the inheritance list
2678should evaluate to a class object. The class's suite is then executed
2679in a new execution frame (see section \ref{execframes}), using a newly
2680created local name space and the original global name space.
2681(Usually, the suite contains only function definitions.) When the
2682class's suite finishes execution, its execution frame is discarded but
2683its local name space is saved. A class object is then created using
2684the inheritance list for the base classes and the saved local name
2685space for the attribute dictionary. The class name is bound to this
2686class object in the original local name space.
2687\index{inheritance}
2688\indexii{class}{name}
2689\indexii{name}{binding}
2690\indexii{execution}{frame}
Guido van Rossumf2612d11991-11-21 13:53:03 +00002691
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002692\chapter{Top-level components}
2693
2694The Python interpreter can get its input from a number of sources:
2695from a script passed to it as standard input or as program argument,
2696typed in interactively, from a module source file, etc. This chapter
2697gives the syntax used in these cases.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002698\index{interpreter}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002699
2700\section{Complete Python programs}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002701\index{program}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002702
2703While a language specification need not prescribe how the language
2704interpreter is invoked, it is useful to have a notion of a complete
2705Python program. A complete Python program is executed in a minimally
2706initialized environment: all built-in and standard modules are
2707available, but none have been initialized, except for \verb\sys\
2708(various system services), \verb\builtin\ (built-in functions,
2709exceptions and \verb\None\) and \verb\__main__\. The latter is used
2710to provide the local and global name space for execution of the
2711complete program.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002712\bimodindex{sys}
2713\bimodindex{__main__}
2714\bimodindex{builtin}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002715
2716The syntax for a complete Python program is that for file input,
2717described in the next section.
2718
2719The interpreter may also be invoked in interactive mode; in this case,
2720it does not read and execute a complete program but reads and executes
2721one statement (possibly compound) at a time. The initial environment
2722is identical to that of a complete program; each statement is executed
2723in the name space of \verb\__main__\.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002724\index{interactive mode}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002725
2726Under {\UNIX}, a complete program can be passed to the interpreter in
2727three forms: with the {\bf -c} {\it string} command line option, as a
2728file passed as the first command line argument, or as standard input.
2729If the file or standard input is a tty device, the interpreter enters
2730interactive mode; otherwise, it executes the file as a complete
2731program.
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002732\index{UNIX}
2733\index{command line}
2734\index{standard input}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002735
2736\section{File input}
2737
2738All input read from non-interactive files has the same form:
2739
2740\begin{verbatim}
2741file_input: (NEWLINE | statement)*
2742\end{verbatim}
2743
2744This syntax is used in the following situations:
2745
2746\begin{itemize}
2747
2748\item when parsing a complete Python program (from a file or from a string);
2749
2750\item when parsing a module;
2751
2752\item when parsing a string passed to \verb\exec()\;
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002753\bifuncindex{exec}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002754
2755\item when parsing a file passed to \verb\execfile()\;
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002756\bifuncindex{execfile}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002757
2758\end{itemize}
2759
2760\section{Interactive input}
2761
2762Input in interactive mode is parsed using the following grammar:
2763
2764\begin{verbatim}
2765interactive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE
2766\end{verbatim}
2767
2768Note that a (top-level) compound statement must be followed by a blank
2769line in interactive mode; this is needed to help the parser detect the
2770end of the input.
2771
2772\section{Expression input}
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002773\index{input}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002774
2775There are two forms of expression input. Both ignore leading
2776whitespace.
2777
2778The string argument to \verb\eval()\ must have the following form:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002779\bifuncindex{eval}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002780
2781\begin{verbatim}
2782eval_input: condition_list NEWLINE*
2783\end{verbatim}
2784
2785The input line read by \verb\input()\ must have the following form:
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002786\bifuncindex{input}
Guido van Rossumcb9d66d1992-03-20 14:59:04 +00002787
2788\begin{verbatim}
2789input_input: condition_list NEWLINE
2790\end{verbatim}
2791
Guido van Rossum2974e3b1992-04-03 14:44:05 +00002792Note: to read `raw' input line without interpretation, you can use the
2793built-in function \verb\raw_input()\ or the \verb\readline()\ method
2794of file objects.
2795\obindex{file}
2796\index{input!raw}
2797\index{raw input}
2798\bifuncindex{raw_index}
2799\ttindex{readline}
2800
Guido van Rossumb5e1c181992-03-06 10:52:59 +00002801\input{ref.ind} % The index
2802
Guido van Rossumf2612d11991-11-21 13:53:03 +00002803\end{document}