blob: 5bd468c5432a3c79ec74ad2e2244b26af7e6d273 [file] [log] [blame]
Guido van Rossumda43a4a1992-08-14 09:17:29 +00001\chapter{Simple statements}
2\indexii{simple}{statement}
3
4Simple statements are comprised within a single logical line.
5Several simple statements may occur on a single line separated
6by semicolons. The syntax for simple statements is:
7
8\begin{verbatim}
9simple_stmt: expression_stmt
10 | assignment_stmt
11 | pass_stmt
12 | del_stmt
13 | print_stmt
14 | return_stmt
15 | raise_stmt
16 | break_stmt
17 | continue_stmt
18 | import_stmt
19 | global_stmt
Guido van Rossuma75d3061993-10-18 17:59:42 +000020 | exec_stmt
Guido van Rossumda43a4a1992-08-14 09:17:29 +000021\end{verbatim}
22
23\section{Expression statements}
24\indexii{expression}{statement}
25
26Expression statements are used (mostly interactively) to compute and
27write a value, or (usually) to call a procedure (a function that
28returns no meaningful result; in Python, procedures return the value
Guido van Rossume9914961994-08-01 12:38:14 +000029\verb@None@):
Guido van Rossumda43a4a1992-08-14 09:17:29 +000030
31\begin{verbatim}
Guido van Rossum611be701995-07-07 23:06:33 +000032expression_stmt: condition_list
Guido van Rossumda43a4a1992-08-14 09:17:29 +000033\end{verbatim}
34
Guido van Rossum611be701995-07-07 23:06:33 +000035An expression statement evaluates the condition list (which may be a
36single condition).
37\indexii{expression}{list}
38
39In interactive mode, if the value is not \verb@None@, it is converted
Guido van Rossumda43a4a1992-08-14 09:17:29 +000040to a string using the rules for string conversions (expressions in
41reverse quotes), and the resulting string is written to standard
42output (see section \ref{print}) on a line by itself.
Guido van Rossum611be701995-07-07 23:06:33 +000043(The exception for \verb@None@ is made so that procedure calls, which
44are syntactically equivalent to expressions, do not cause any output.)
Guido van Rossumda43a4a1992-08-14 09:17:29 +000045\ttindex{None}
46\indexii{string}{conversion}
47\index{output}
48\indexii{standard}{output}
49\indexii{writing}{values}
Guido van Rossumda43a4a1992-08-14 09:17:29 +000050\indexii{procedure}{call}
51
52\section{Assignment statements}
53\indexii{assignment}{statement}
54
55Assignment statements are used to (re)bind names to values and to
56modify attributes or items of mutable objects:
57\indexii{binding}{name}
58\indexii{rebinding}{name}
59\obindex{mutable}
60\indexii{attribute}{assignment}
61
62\begin{verbatim}
63assignment_stmt: (target_list "=")+ expression_list
64target_list: target ("," target)* [","]
65target: identifier | "(" target_list ")" | "[" target_list "]"
66 | attributeref | subscription | slicing
67\end{verbatim}
68
69(See section \ref{primaries} for the syntax definitions for the last
70three symbols.)
71
72An assignment statement evaluates the expression list (remember that
73this can be a single expression or a comma-separated list, the latter
74yielding a tuple) and assigns the single resulting object to each of
75the target lists, from left to right.
76\indexii{expression}{list}
77
78Assignment is defined recursively depending on the form of the target
79(list). When a target is part of a mutable object (an attribute
80reference, subscription or slicing), the mutable object must
81ultimately perform the assignment and decide about its validity, and
82may raise an exception if the assignment is unacceptable. The rules
83observed by various types and the exceptions raised are given with the
84definition of the object types (see section \ref{types}).
85\index{target}
86\indexii{target}{list}
87
88Assignment of an object to a target list is recursively defined as
89follows.
90\indexiii{target}{list}{assignment}
91
92\begin{itemize}
93\item
94If the target list is a single target: the object is assigned to that
95target.
96
97\item
98If the target list is a comma-separated list of targets: the object
99must be a tuple with the same number of items as the list contains
100targets, and the items are assigned, from left to right, to the
101corresponding targets.
102
103\end{itemize}
104
105Assignment of an object to a single target is recursively defined as
106follows.
107
108\begin{itemize} % nested
109
110\item
111If the target is an identifier (name):
112
113\begin{itemize}
114
115\item
Guido van Rossume9914961994-08-01 12:38:14 +0000116If the name does not occur in a \verb@global@ statement in the current
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000117code block: the name is bound to the object in the current local name
118space.
119\stindex{global}
120
121\item
122Otherwise: the name is bound to the object in the current global name
123space.
124
125\end{itemize} % nested
126
127The name is rebound if it was already bound.
128
129\item
130If the target is a target list enclosed in parentheses: the object is
131assigned to that target list as described above.
132
133\item
134If the target is a target list enclosed in square brackets: the object
135must be a list with the same number of items as the target list
136contains targets, and its items are assigned, from left to right, to
137the corresponding targets.
138
139\item
140If the target is an attribute reference: The primary expression in the
141reference is evaluated. It should yield an object with assignable
Guido van Rossume9914961994-08-01 12:38:14 +0000142attributes; if this is not the case, \verb@TypeError@ is raised. That
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000143object is then asked to assign the assigned object to the given
144attribute; if it cannot perform the assignment, it raises an exception
Guido van Rossume9914961994-08-01 12:38:14 +0000145(usually but not necessarily \verb@AttributeError@).
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000146\indexii{attribute}{assignment}
147
148\item
149If the target is a subscription: The primary expression in the
150reference is evaluated. It should yield either a mutable sequence
151(list) object or a mapping (dictionary) object. Next, the subscript
152expression is evaluated.
153\indexii{subscription}{assignment}
154\obindex{mutable}
155
156If the primary is a mutable sequence object (a list), the subscript
157must yield a plain integer. If it is negative, the sequence's length
158is added to it. The resulting value must be a nonnegative integer
159less than the sequence's length, and the sequence is asked to assign
160the assigned object to its item with that index. If the index is out
Guido van Rossume9914961994-08-01 12:38:14 +0000161of range, \verb@IndexError@ is raised (assignment to a subscripted
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000162sequence cannot add new items to a list).
163\obindex{sequence}
164\obindex{list}
165
166If the primary is a mapping (dictionary) object, the subscript must
167have a type compatible with the mapping's key type, and the mapping is
Guido van Rossum31cce971995-01-04 19:17:34 +0000168then asked to create a key/datum pair which maps the subscript to
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000169the assigned object. This can either replace an existing key/value
170pair with the same key value, or insert a new key/value pair (if no
171key with the same value existed).
172\obindex{mapping}
173\obindex{dictionary}
174
175\item
176If the target is a slicing: The primary expression in the reference is
Guido van Rossume9914961994-08-01 12:38:14 +0000177evaluated. It should yield a mutable sequence object (e.g. a list). The
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000178assigned object should be a sequence object of the same type. Next,
179the lower and upper bound expressions are evaluated, insofar they are
180present; defaults are zero and the sequence's length. The bounds
181should evaluate to (small) integers. If either bound is negative, the
182sequence's length is added to it. The resulting bounds are clipped to
183lie between zero and the sequence's length, inclusive. Finally, the
Guido van Rossume9914961994-08-01 12:38:14 +0000184sequence object is asked to replace the slice with the items of the
185assigned sequence. The length of the slice may be different from the
186length of the assigned sequence, thus changing the length of the
187target sequence, if the object allows it.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000188\indexii{slicing}{assignment}
189
190\end{itemize}
191
Guido van Rossumbd851cd1994-08-23 13:26:22 +0000192(In the current implementation, the syntax for targets is taken
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000193to be the same as for expressions, and invalid syntax is rejected
194during the code generation phase, causing less detailed error
195messages.)
196
Guido van Rossumbd851cd1994-08-23 13:26:22 +0000197WARNING: Although the definition of assignment implies that overlaps
198between the left-hand side and the right-hand side are `safe' (e.g.
199\verb@a, b = b, a@ swaps two variables), overlaps within the
200collection of assigned-to variables are not safe! For instance, the
201following program prints \code@[0, 2]@:
202
203\begin{verbatim}
204x = [0, 1]
205i = 0
206i, x[i] = 1, 2
207print x
208\end{verbatim}
209
210
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000211\section{The {\tt pass} statement}
212\stindex{pass}
213
214\begin{verbatim}
215pass_stmt: "pass"
216\end{verbatim}
217
Guido van Rossume9914961994-08-01 12:38:14 +0000218\verb@pass@ is a null operation --- when it is executed, nothing
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000219happens. It is useful as a placeholder when a statement is
220required syntactically, but no code needs to be executed, for example:
221\indexii{null}{operation}
222
223\begin{verbatim}
224def f(arg): pass # a function that does nothing (yet)
225
Guido van Rossum611be701995-07-07 23:06:33 +0000226class C: pass # a class with no methods (yet)
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000227\end{verbatim}
228
229\section{The {\tt del} statement}
230\stindex{del}
231
232\begin{verbatim}
233del_stmt: "del" target_list
234\end{verbatim}
235
236Deletion is recursively defined very similar to the way assignment is
237defined. Rather that spelling it out in full details, here are some
238hints.
239\indexii{deletion}{target}
240\indexiii{deletion}{target}{list}
241
242Deletion of a target list recursively deletes each target, from left
243to right.
244
245Deletion of a name removes the binding of that name (which must exist)
246from the local or global name space, depending on whether the name
Guido van Rossume9914961994-08-01 12:38:14 +0000247occurs in a \verb@global@ statement in the same code block.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000248\stindex{global}
249\indexii{unbinding}{name}
250
251Deletion of attribute references, subscriptions and slicings
252is passed to the primary object involved; deletion of a slicing
253is in general equivalent to assignment of an empty slice of the
254right type (but even this is determined by the sliced object).
255\indexii{attribute}{deletion}
256
257\section{The {\tt print} statement} \label{print}
258\stindex{print}
259
260\begin{verbatim}
261print_stmt: "print" [ condition ("," condition)* [","] ]
262\end{verbatim}
263
Guido van Rossume9914961994-08-01 12:38:14 +0000264\verb@print@ evaluates each condition in turn and writes the resulting
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000265object to standard output (see below). If an object is not a string,
266it is first converted to a string using the rules for string
267conversions. The (resulting or original) string is then written. A
268space is written before each object is (converted and) written, unless
269the output system believes it is positioned at the beginning of a
270line. This is the case: (1) when no characters have yet been written
271to standard output; or (2) when the last character written to standard
272output is \verb/\n/; or (3) when the last write operation on standard
Guido van Rossume9914961994-08-01 12:38:14 +0000273output was not a \verb@print@ statement. (In some cases it may be
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000274functional to write an empty string to standard output for this
275reason.)
276\index{output}
277\indexii{writing}{values}
278
Guido van Rossume9914961994-08-01 12:38:14 +0000279A \verb/"\n"/ character is written at the end, unless the \verb@print@
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000280statement ends with a comma. This is the only action if the statement
Guido van Rossume9914961994-08-01 12:38:14 +0000281contains just the keyword \verb@print@.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000282\indexii{trailing}{comma}
283\indexii{newline}{suppression}
284
Guido van Rossume9914961994-08-01 12:38:14 +0000285Standard output is defined as the file object named \verb@stdout@
286in the built-in module \verb@sys@. If no such object exists,
287or if it is not a writable file, a \verb@RuntimeError@ exception is raised.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000288(The original implementation attempts to write to the system's original
289standard output instead, but this is not safe, and should be fixed.)
290\indexii{standard}{output}
291\bimodindex{sys}
292\ttindex{stdout}
293\exindex{RuntimeError}
294
295\section{The {\tt return} statement}
296\stindex{return}
297
298\begin{verbatim}
299return_stmt: "return" [condition_list]
300\end{verbatim}
301
Guido van Rossume9914961994-08-01 12:38:14 +0000302\verb@return@ may only occur syntactically nested in a function
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000303definition, not within a nested class definition.
304\indexii{function}{definition}
305\indexii{class}{definition}
306
Guido van Rossume9914961994-08-01 12:38:14 +0000307If a condition list is present, it is evaluated, else \verb@None@
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000308is substituted.
309
Guido van Rossume9914961994-08-01 12:38:14 +0000310\verb@return@ leaves the current function call with the condition
311list (or \verb@None@) as return value.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000312
Guido van Rossume9914961994-08-01 12:38:14 +0000313When \verb@return@ passes control out of a \verb@try@ statement
314with a \verb@finally@ clause, that finally clause is executed
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000315before really leaving the function.
316\kwindex{finally}
317
318\section{The {\tt raise} statement}
319\stindex{raise}
320
321\begin{verbatim}
Guido van Rossum611be701995-07-07 23:06:33 +0000322raise_stmt: "raise" condition ["," condition ["," condition]]
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000323\end{verbatim}
324
Guido van Rossume9914961994-08-01 12:38:14 +0000325\verb@raise@ evaluates its first condition, which must yield
Guido van Rossumeb8b0d21995-02-07 14:37:17 +0000326a string, class, or instance object. If there is a second condition,
327this is evaluated, else \verb@None@ is substituted. If the first
328condition is a class object, then the second condition must be an
329instance of that class or one of its derivatives. If the first
330condition is an instance object, the second condition must be
331\verb@None@.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000332\index{exception}
333\indexii{raising}{exception}
334
Guido van Rossumeb8b0d21995-02-07 14:37:17 +0000335If the first object is a class or string, it then raises the exception
336identified by the first object, with the second one (or \verb@None@)
337as its parameter. If the first object is an instance, it raises the
338exception identified by the class of the object, with the instance as
Guido van Rossum611be701995-07-07 23:06:33 +0000339its parameter (and there should be no second object, or the second
340object should be \verb@None@).
341
342If a third object is present, and it it not \verb@None@, it should be
343a traceback object (see section \ref{traceback}), and it is
344substituted instead of the current location as the place where the
345exception occurred. This is useful to re-raise an exception
346transparently in an except clause.
347\obindex{traceback}
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000348
349\section{The {\tt break} statement}
350\stindex{break}
351
352\begin{verbatim}
353break_stmt: "break"
354\end{verbatim}
355
Guido van Rossume9914961994-08-01 12:38:14 +0000356\verb@break@ may only occur syntactically nested in a \verb@for@
357or \verb@while@ loop, but not nested in a function or class definition
358within that loop.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000359\stindex{for}
360\stindex{while}
361\indexii{loop}{statement}
362
Guido van Rossume9914961994-08-01 12:38:14 +0000363It terminates the nearest enclosing loop, skipping the optional
364\verb@else@ clause if the loop has one.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000365\kwindex{else}
366
Guido van Rossume9914961994-08-01 12:38:14 +0000367If a \verb@for@ loop is terminated by \verb@break@, the loop control
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000368target keeps its current value.
369\indexii{loop control}{target}
370
Guido van Rossume9914961994-08-01 12:38:14 +0000371When \verb@break@ passes control out of a \verb@try@ statement
372with a \verb@finally@ clause, that finally clause is executed
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000373before really leaving the loop.
374\kwindex{finally}
375
376\section{The {\tt continue} statement}
377\stindex{continue}
378
379\begin{verbatim}
380continue_stmt: "continue"
381\end{verbatim}
382
Guido van Rossume9914961994-08-01 12:38:14 +0000383\verb@continue@ may only occur syntactically nested in a \verb@for@ or
384\verb@while@ loop, but not nested in a function or class definition or
385\verb@try@ statement within that loop.\footnote{Except that it may
Guido van Rossum31cce971995-01-04 19:17:34 +0000386currently occur within an {\tt except} clause.}
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000387\stindex{for}
388\stindex{while}
389\indexii{loop}{statement}
390\kwindex{finally}
391
392It continues with the next cycle of the nearest enclosing loop.
393
394\section{The {\tt import} statement} \label{import}
395\stindex{import}
396
397\begin{verbatim}
398import_stmt: "import" identifier ("," identifier)*
399 | "from" identifier "import" identifier ("," identifier)*
400 | "from" identifier "import" "*"
401\end{verbatim}
402
403Import statements are executed in two steps: (1) find a module, and
404initialize it if necessary; (2) define a name or names in the local
Guido van Rossume9914961994-08-01 12:38:14 +0000405name space (of the scope where the \verb@import@ statement occurs).
406The first form (without \verb@from@) repeats these steps for each
407identifier in the list, the \verb@from@ form performs them once, with
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000408the first identifier specifying the module name.
409\indexii{importing}{module}
410\indexii{name}{binding}
411\kwindex{from}
412
413The system maintains a table of modules that have been initialized,
414indexed by module name. (The current implementation makes this table
Guido van Rossume9914961994-08-01 12:38:14 +0000415accessible as \verb@sys.modules@.) When a module name is found in
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000416this table, step (1) is finished. If not, a search for a module
417definition is started. This first looks for a built-in module
418definition, and if no built-in module if the given name is found, it
419searches a user-specified list of directories for a file whose name is
Guido van Rossume9914961994-08-01 12:38:14 +0000420the module name with extension \verb@".py"@. (The current
421implementation uses the list of strings \verb@sys.path@ as the search
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000422path; it is initialized from the shell environment variable
Guido van Rossume9914961994-08-01 12:38:14 +0000423\verb@$PYTHONPATH@, with an installation-dependent default.)
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000424\ttindex{modules}
425\ttindex{sys.modules}
426\indexii{module}{name}
427\indexii{built-in}{module}
428\indexii{user-defined}{module}
429\bimodindex{sys}
430\ttindex{path}
431\ttindex{sys.path}
432\indexii{filename}{extension}
433
434If a built-in module is found, its built-in initialization code is
435executed and step (1) is finished. If no matching file is found,
Guido van Rossume9914961994-08-01 12:38:14 +0000436\verb@ImportError@ is raised. If a file is found, it is parsed,
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000437yielding an executable code block. If a syntax error occurs,
Guido van Rossume9914961994-08-01 12:38:14 +0000438\verb@SyntaxError@ is raised. Otherwise, an empty module of the given
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000439name is created and inserted in the module table, and then the code
440block is executed in the context of this module. Exceptions during
441this execution terminate step (1).
442\indexii{module}{initialization}
443\exindex{SyntaxError}
444\exindex{ImportError}
445\index{code block}
446
447When step (1) finishes without raising an exception, step (2) can
448begin.
449
Guido van Rossume9914961994-08-01 12:38:14 +0000450The first form of \verb@import@ statement binds the module name in the
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000451local name space to the module object, and then goes on to import the
Guido van Rossume9914961994-08-01 12:38:14 +0000452next identifier, if any. The \verb@from@ from does not bind the
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000453module name: it goes through the list of identifiers, looks each one
454of them up in the module found in step (1), and binds the name in the
455local name space to the object thus found. If a name is not found,
Guido van Rossume9914961994-08-01 12:38:14 +0000456\verb@ImportError@ is raised. If the list of identifiers is replaced
457by a star (\verb@*@), all names defined in the module are bound,
458except those beginning with an underscore(\verb@_@).
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000459\indexii{name}{binding}
460\exindex{ImportError}
461
Guido van Rossume9914961994-08-01 12:38:14 +0000462Names bound by import statements may not occur in \verb@global@
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000463statements in the same scope.
464\stindex{global}
465
Guido van Rossume9914961994-08-01 12:38:14 +0000466The \verb@from@ form with \verb@*@ may only occur in a module scope.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000467\kwindex{from}
468\ttindex{from ... import *}
469
470(The current implementation does not enforce the latter two
471restrictions, but programs should not abuse this freedom, as future
472implementations may enforce them or silently change the meaning of the
473program.)
474
475\section{The {\tt global} statement} \label{global}
476\stindex{global}
477
478\begin{verbatim}
479global_stmt: "global" identifier ("," identifier)*
480\end{verbatim}
481
Guido van Rossume9914961994-08-01 12:38:14 +0000482The \verb@global@ statement is a declaration which holds for the
Guido van Rossum7710f1f1996-06-26 19:26:40 +0000483entire current code block. It means that the listed identifiers are to be
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000484interpreted as globals. While {\em using} global names is automatic
485if they are not defined in the local scope, {\em assigning} to global
Guido van Rossume9914961994-08-01 12:38:14 +0000486names would be impossible without \verb@global@.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000487\indexiii{global}{name}{binding}
488
Guido van Rossume9914961994-08-01 12:38:14 +0000489Names listed in a \verb@global@ statement must not be used in the same
Guido van Rossum7710f1f1996-06-26 19:26:40 +0000490code block before that \verb@global@ statement is executed.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000491
Guido van Rossume9914961994-08-01 12:38:14 +0000492Names listed in a \verb@global@ statement must not be defined as formal
493parameters or in a \verb@for@ loop control target, \verb@class@
494definition, function definition, or \verb@import@ statement.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000495
496(The current implementation does not enforce the latter two
497restrictions, but programs should not abuse this freedom, as future
498implementations may enforce them or silently change the meaning of the
499program.)
Guido van Rossuma75d3061993-10-18 17:59:42 +0000500
Guido van Rossum7710f1f1996-06-26 19:26:40 +0000501Note: the \verb@global@ is a directive to the parser. Therefore, it
502applies only to code parsed at the same time as the \verb@global@
503statement. In particular, a \verb@global@ statement contained in an
504\verb@exec@ statement does not affect the code block {\em containing}
505the \verb@exec@ statement, and code contained in an \verb@exec@
506statement is unaffected by \verb@global@ statements in the code
507containing the \verb@exec@ statement. The same applies to the
508\verb@eval()@, \verb@execfie()@ and \verb@compile()@ functions.
509\stindex{exec}
510\ttindex{eval}
511\ttindex{execfile}
512\ttindex{compile}