blob: cb257a3e4c837aee1174441e09a38f4d2e364427 [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
20\end{verbatim}
21
22\section{Expression statements}
23\indexii{expression}{statement}
24
25Expression statements are used (mostly interactively) to compute and
26write a value, or (usually) to call a procedure (a function that
27returns no meaningful result; in Python, procedures return the value
28\verb\None\):
29
30\begin{verbatim}
31expression_stmt: expression_list
32\end{verbatim}
33
34An expression statement evaluates the expression list (which may be a
35single expression). If the value is not \verb\None\, it is converted
36to a string using the rules for string conversions (expressions in
37reverse quotes), and the resulting string is written to standard
38output (see section \ref{print}) on a line by itself.
39\indexii{expression}{list}
40\ttindex{None}
41\indexii{string}{conversion}
42\index{output}
43\indexii{standard}{output}
44\indexii{writing}{values}
45
46(The exception for \verb\None\ is made so that procedure calls, which
47are syntactically equivalent to expressions, do not cause any output.
48A tuple with only \verb\None\ items is written normally.)
49\indexii{procedure}{call}
50
51\section{Assignment statements}
52\indexii{assignment}{statement}
53
54Assignment statements are used to (re)bind names to values and to
55modify attributes or items of mutable objects:
56\indexii{binding}{name}
57\indexii{rebinding}{name}
58\obindex{mutable}
59\indexii{attribute}{assignment}
60
61\begin{verbatim}
62assignment_stmt: (target_list "=")+ expression_list
63target_list: target ("," target)* [","]
64target: identifier | "(" target_list ")" | "[" target_list "]"
65 | attributeref | subscription | slicing
66\end{verbatim}
67
68(See section \ref{primaries} for the syntax definitions for the last
69three symbols.)
70
71An assignment statement evaluates the expression list (remember that
72this can be a single expression or a comma-separated list, the latter
73yielding a tuple) and assigns the single resulting object to each of
74the target lists, from left to right.
75\indexii{expression}{list}
76
77Assignment is defined recursively depending on the form of the target
78(list). When a target is part of a mutable object (an attribute
79reference, subscription or slicing), the mutable object must
80ultimately perform the assignment and decide about its validity, and
81may raise an exception if the assignment is unacceptable. The rules
82observed by various types and the exceptions raised are given with the
83definition of the object types (see section \ref{types}).
84\index{target}
85\indexii{target}{list}
86
87Assignment of an object to a target list is recursively defined as
88follows.
89\indexiii{target}{list}{assignment}
90
91\begin{itemize}
92\item
93If the target list is a single target: the object is assigned to that
94target.
95
96\item
97If the target list is a comma-separated list of targets: the object
98must be a tuple with the same number of items as the list contains
99targets, and the items are assigned, from left to right, to the
100corresponding targets.
101
102\end{itemize}
103
104Assignment of an object to a single target is recursively defined as
105follows.
106
107\begin{itemize} % nested
108
109\item
110If the target is an identifier (name):
111
112\begin{itemize}
113
114\item
115If the name does not occur in a \verb\global\ statement in the current
116code block: the name is bound to the object in the current local name
117space.
118\stindex{global}
119
120\item
121Otherwise: the name is bound to the object in the current global name
122space.
123
124\end{itemize} % nested
125
126The name is rebound if it was already bound.
127
128\item
129If the target is a target list enclosed in parentheses: the object is
130assigned to that target list as described above.
131
132\item
133If the target is a target list enclosed in square brackets: the object
134must be a list with the same number of items as the target list
135contains targets, and its items are assigned, from left to right, to
136the corresponding targets.
137
138\item
139If the target is an attribute reference: The primary expression in the
140reference is evaluated. It should yield an object with assignable
141attributes; if this is not the case, \verb\TypeError\ is raised. That
142object is then asked to assign the assigned object to the given
143attribute; if it cannot perform the assignment, it raises an exception
144(usually but not necessarily \verb\AttributeError\).
145\indexii{attribute}{assignment}
146
147\item
148If the target is a subscription: The primary expression in the
149reference is evaluated. It should yield either a mutable sequence
150(list) object or a mapping (dictionary) object. Next, the subscript
151expression is evaluated.
152\indexii{subscription}{assignment}
153\obindex{mutable}
154
155If the primary is a mutable sequence object (a list), the subscript
156must yield a plain integer. If it is negative, the sequence's length
157is added to it. The resulting value must be a nonnegative integer
158less than the sequence's length, and the sequence is asked to assign
159the assigned object to its item with that index. If the index is out
160of range, \verb\IndexError\ is raised (assignment to a subscripted
161sequence cannot add new items to a list).
162\obindex{sequence}
163\obindex{list}
164
165If the primary is a mapping (dictionary) object, the subscript must
166have a type compatible with the mapping's key type, and the mapping is
167then asked to to create a key/datum pair which maps the subscript to
168the assigned object. This can either replace an existing key/value
169pair with the same key value, or insert a new key/value pair (if no
170key with the same value existed).
171\obindex{mapping}
172\obindex{dictionary}
173
174\item
175If the target is a slicing: The primary expression in the reference is
176evaluated. It should yield a mutable sequence (list) object. The
177assigned object should be a sequence object of the same type. Next,
178the lower and upper bound expressions are evaluated, insofar they are
179present; defaults are zero and the sequence's length. The bounds
180should evaluate to (small) integers. If either bound is negative, the
181sequence's length is added to it. The resulting bounds are clipped to
182lie between zero and the sequence's length, inclusive. Finally, the
183sequence object is asked to replace the items indicated by the slice
184with the items of the assigned sequence. This may change the
185sequence's length, if it allows it.
186\indexii{slicing}{assignment}
187
188\end{itemize}
189
190(In the original implementation, the syntax for targets is taken
191to be the same as for expressions, and invalid syntax is rejected
192during the code generation phase, causing less detailed error
193messages.)
194
195\section{The {\tt pass} statement}
196\stindex{pass}
197
198\begin{verbatim}
199pass_stmt: "pass"
200\end{verbatim}
201
202\verb\pass\ is a null operation --- when it is executed, nothing
203happens. It is useful as a placeholder when a statement is
204required syntactically, but no code needs to be executed, for example:
205\indexii{null}{operation}
206
207\begin{verbatim}
208def f(arg): pass # a function that does nothing (yet)
209
210class C: pass # an class with no methods (yet)
211\end{verbatim}
212
213\section{The {\tt del} statement}
214\stindex{del}
215
216\begin{verbatim}
217del_stmt: "del" target_list
218\end{verbatim}
219
220Deletion is recursively defined very similar to the way assignment is
221defined. Rather that spelling it out in full details, here are some
222hints.
223\indexii{deletion}{target}
224\indexiii{deletion}{target}{list}
225
226Deletion of a target list recursively deletes each target, from left
227to right.
228
229Deletion of a name removes the binding of that name (which must exist)
230from the local or global name space, depending on whether the name
231occurs in a \verb\global\ statement in the same code block.
232\stindex{global}
233\indexii{unbinding}{name}
234
235Deletion of attribute references, subscriptions and slicings
236is passed to the primary object involved; deletion of a slicing
237is in general equivalent to assignment of an empty slice of the
238right type (but even this is determined by the sliced object).
239\indexii{attribute}{deletion}
240
241\section{The {\tt print} statement} \label{print}
242\stindex{print}
243
244\begin{verbatim}
245print_stmt: "print" [ condition ("," condition)* [","] ]
246\end{verbatim}
247
248\verb\print\ evaluates each condition in turn and writes the resulting
249object to standard output (see below). If an object is not a string,
250it is first converted to a string using the rules for string
251conversions. The (resulting or original) string is then written. A
252space is written before each object is (converted and) written, unless
253the output system believes it is positioned at the beginning of a
254line. This is the case: (1) when no characters have yet been written
255to standard output; or (2) when the last character written to standard
256output is \verb/\n/; or (3) when the last write operation on standard
257output was not a \verb\print\ statement. (In some cases it may be
258functional to write an empty string to standard output for this
259reason.)
260\index{output}
261\indexii{writing}{values}
262
263A \verb/"\n"/ character is written at the end, unless the \verb\print\
264statement ends with a comma. This is the only action if the statement
265contains just the keyword \verb\print\.
266\indexii{trailing}{comma}
267\indexii{newline}{suppression}
268
269Standard output is defined as the file object named \verb\stdout\
270in the built-in module \verb\sys\. If no such object exists,
271or if it is not a writable file, a \verb\RuntimeError\ exception is raised.
272(The original implementation attempts to write to the system's original
273standard output instead, but this is not safe, and should be fixed.)
274\indexii{standard}{output}
275\bimodindex{sys}
276\ttindex{stdout}
277\exindex{RuntimeError}
278
279\section{The {\tt return} statement}
280\stindex{return}
281
282\begin{verbatim}
283return_stmt: "return" [condition_list]
284\end{verbatim}
285
286\verb\return\ may only occur syntactically nested in a function
287definition, not within a nested class definition.
288\indexii{function}{definition}
289\indexii{class}{definition}
290
291If a condition list is present, it is evaluated, else \verb\None\
292is substituted.
293
294\verb\return\ leaves the current function call with the condition
295list (or \verb\None\) as return value.
296
297When \verb\return\ passes control out of a \verb\try\ statement
298with a \verb\finally\ clause, that finally clause is executed
299before really leaving the function.
300\kwindex{finally}
301
302\section{The {\tt raise} statement}
303\stindex{raise}
304
305\begin{verbatim}
306raise_stmt: "raise" condition ["," condition]
307\end{verbatim}
308
309\verb\raise\ evaluates its first condition, which must yield
310a string object. If there is a second condition, this is evaluated,
311else \verb\None\ is substituted.
312\index{exception}
313\indexii{raising}{exception}
314
315It then raises the exception identified by the first object,
316with the second one (or \verb\None\) as its parameter.
317
318\section{The {\tt break} statement}
319\stindex{break}
320
321\begin{verbatim}
322break_stmt: "break"
323\end{verbatim}
324
325\verb\break\ may only occur syntactically nested in a \verb\for\
326or \verb\while\ loop, not nested in a function or class definition.
327\stindex{for}
328\stindex{while}
329\indexii{loop}{statement}
330
331It terminates the neares enclosing loop, skipping the optional
332\verb\else\ clause if the loop has one.
333\kwindex{else}
334
335If a \verb\for\ loop is terminated by \verb\break\, the loop control
336target keeps its current value.
337\indexii{loop control}{target}
338
339When \verb\break\ passes control out of a \verb\try\ statement
340with a \verb\finally\ clause, that finally clause is executed
341before really leaving the loop.
342\kwindex{finally}
343
344\section{The {\tt continue} statement}
345\stindex{continue}
346
347\begin{verbatim}
348continue_stmt: "continue"
349\end{verbatim}
350
351\verb\continue\ may only occur syntactically nested in a \verb\for\ or
352\verb\while\ loop, not nested in a function or class definition, and
353not nested in the \verb\try\ clause of a \verb\try\ statement with a
354\verb\finally\ clause (it may occur nested in a \verb\except\ or
355\verb\finally\ clause of a \verb\try\ statement though).
356\stindex{for}
357\stindex{while}
358\indexii{loop}{statement}
359\kwindex{finally}
360
361It continues with the next cycle of the nearest enclosing loop.
362
363\section{The {\tt import} statement} \label{import}
364\stindex{import}
365
366\begin{verbatim}
367import_stmt: "import" identifier ("," identifier)*
368 | "from" identifier "import" identifier ("," identifier)*
369 | "from" identifier "import" "*"
370\end{verbatim}
371
372Import statements are executed in two steps: (1) find a module, and
373initialize it if necessary; (2) define a name or names in the local
374name space (of the scope where the \verb\import\ statement occurs).
375The first form (without \verb\from\) repeats these steps for each
376identifier in the list, the \verb\from\ form performs them once, with
377the first identifier specifying the module name.
378\indexii{importing}{module}
379\indexii{name}{binding}
380\kwindex{from}
381
382The system maintains a table of modules that have been initialized,
383indexed by module name. (The current implementation makes this table
384accessible as \verb\sys.modules\.) When a module name is found in
385this table, step (1) is finished. If not, a search for a module
386definition is started. This first looks for a built-in module
387definition, and if no built-in module if the given name is found, it
388searches a user-specified list of directories for a file whose name is
389the module name with extension \verb\".py"\. (The current
390implementation uses the list of strings \verb\sys.path\ as the search
391path; it is initialized from the shell environment variable
392\verb\$PYTHONPATH\, with an installation-dependent default.)
393\ttindex{modules}
394\ttindex{sys.modules}
395\indexii{module}{name}
396\indexii{built-in}{module}
397\indexii{user-defined}{module}
398\bimodindex{sys}
399\ttindex{path}
400\ttindex{sys.path}
401\indexii{filename}{extension}
402
403If a built-in module is found, its built-in initialization code is
404executed and step (1) is finished. If no matching file is found,
405\verb\ImportError\ is raised. If a file is found, it is parsed,
406yielding an executable code block. If a syntax error occurs,
407\verb\SyntaxError\ is raised. Otherwise, an empty module of the given
408name is created and inserted in the module table, and then the code
409block is executed in the context of this module. Exceptions during
410this execution terminate step (1).
411\indexii{module}{initialization}
412\exindex{SyntaxError}
413\exindex{ImportError}
414\index{code block}
415
416When step (1) finishes without raising an exception, step (2) can
417begin.
418
419The first form of \verb\import\ statement binds the module name in the
420local name space to the module object, and then goes on to import the
421next identifier, if any. The \verb\from\ from does not bind the
422module name: it goes through the list of identifiers, looks each one
423of them up in the module found in step (1), and binds the name in the
424local name space to the object thus found. If a name is not found,
425\verb\ImportError\ is raised. If the list of identifiers is replaced
426by a star (\verb\*\), all names defined in the module are bound,
427except those beginning with an underscore(\verb\_\).
428\indexii{name}{binding}
429\exindex{ImportError}
430
431Names bound by import statements may not occur in \verb\global\
432statements in the same scope.
433\stindex{global}
434
435The \verb\from\ form with \verb\*\ may only occur in a module scope.
436\kwindex{from}
437\ttindex{from ... import *}
438
439(The current implementation does not enforce the latter two
440restrictions, but programs should not abuse this freedom, as future
441implementations may enforce them or silently change the meaning of the
442program.)
443
444\section{The {\tt global} statement} \label{global}
445\stindex{global}
446
447\begin{verbatim}
448global_stmt: "global" identifier ("," identifier)*
449\end{verbatim}
450
451The \verb\global\ statement is a declaration which holds for the
452entire current scope. It means that the listed identifiers are to be
453interpreted as globals. While {\em using} global names is automatic
454if they are not defined in the local scope, {\em assigning} to global
455names would be impossible without \verb\global\.
456\indexiii{global}{name}{binding}
457
458Names listed in a \verb\global\ statement must not be used in the same
459scope before that \verb\global\ statement is executed.
460
461Names listed in a \verb\global\ statement must not be defined as formal
462parameters or in a \verb\for\ loop control target, \verb\class\
463definition, function definition, or \verb\import\ statement.
464
465(The current implementation does not enforce the latter two
466restrictions, but programs should not abuse this freedom, as future
467implementations may enforce them or silently change the meaning of the
468program.)