1 \chapter{Simple statements
\label{simple
}}
2 \indexii{simple
}{statement
}
4 Simple statements are comprised within a single logical line.
5 Several simple statements may occur on a single line separated
6 by semicolons. The syntax for simple statements is:
9 simple_stmt: expression_stmt
12 | augmented_assignment_stmt
25 \section{Expression statements
\label{exprstmts
}}
26 \indexii{expression
}{statement
}
28 Expression statements are used (mostly interactively) to compute and
29 write a value, or (usually) to call a procedure (a function that
30 returns no meaningful result; in Python, procedures return the value
31 \code{None
}). Other uses of expression statements are allowed and
32 occasionally useful. The syntax for an expression statement is:
35 expression_stmt: expression_list
38 An expression statement evaluates the expression list (which may be a
40 \indexii{expression
}{list
}
42 In interactive mode, if the value is not
\code{None
}, it is converted
43 to a string using the built-in
\function{repr()
}\bifuncindex{repr
}
44 function and the resulting string is written to standard output (see
45 section
\ref{print
}) on a line by itself. (Expression statements
46 yielding None are not written, so that procedure calls do not cause
49 \indexii{string
}{conversion
}
51 \indexii{standard
}{output
}
52 \indexii{writing
}{values
}
53 \indexii{procedure
}{call
}
55 \section{Assert statements
\label{assert
}}
57 Assert statements
\stindex{assert
} are a convenient way to insert
58 debugging assertions
\indexii{debugging
}{assertions
} into a program:
61 assert_statement: "assert" expression
["," expression
]
64 The simple form,
\samp{assert expression
}, is equivalent to
68 if not expression: raise AssertionError
71 The extended form,
\samp{assert expression1, expression2
}, is
76 if not expression1: raise AssertionError, expression2
79 These equivalences assume that
\code{__debug__
}\ttindex{__debug__
} and
80 \exception{AssertionError
}\exindex{AssertionError
} refer to the built-in
81 variables with those names. In the current implementation, the
82 built-in variable
\code{__debug__
} is
1 under normal circumstances,
0
83 when optimization is requested (command line option -O). The current
84 code generator emits no code for an assert statement when optimization
85 is requested at compile time. Note that it is unnecessary to include
86 the source code for the expression that failed in the error message;
87 it will be displayed as part of the stack trace.
89 Assignments to
\code{__debug__
} are illegal. The value for the
90 built-in variable is determined when the interpreter starts.
92 \section{Assignment statements
\label{assignment
}}
94 Assignment statements
\indexii{assignment
}{statement
} are used to
95 (re)bind names to values and to modify attributes or items of mutable
97 \indexii{binding
}{name
}
98 \indexii{rebinding
}{name
}
100 \indexii{attribute
}{assignment
}
103 assignment_stmt: (target_list "=")+ expression_list
104 target_list: target ("," target)*
[","
]
105 target: identifier | "(" target_list ")" | "
[" target_list "
]"
106 | attributeref | subscription | slicing
109 (See section
\ref{primaries
} for the syntax definitions for the last
112 An assignment statement evaluates the expression list (remember that
113 this can be a single expression or a comma-separated list, the latter
114 yielding a tuple) and assigns the single resulting object to each of
115 the target lists, from left to right.
116 \indexii{expression
}{list
}
118 Assignment is defined recursively depending on the form of the target
119 (list). When a target is part of a mutable object (an attribute
120 reference, subscription or slicing), the mutable object must
121 ultimately perform the assignment and decide about its validity, and
122 may raise an exception if the assignment is unacceptable. The rules
123 observed by various types and the exceptions raised are given with the
124 definition of the object types (see section
\ref{types
}).
126 \indexii{target
}{list
}
128 Assignment of an object to a target list is recursively defined as
130 \indexiii{target
}{list
}{assignment
}
134 If the target list is a single target: The object is assigned to that
138 If the target list is a comma-separated list of targets: The object
139 must be a sequence with the same number of items as the there are
140 targets in the target list, and the items are assigned, from left to
141 right, to the corresponding targets. (This rule is relaxed as of
142 Python
1.5; in earlier versions, the object had to be a tuple. Since
143 strings are sequences, an assignment like
\samp{a, b = "xy"
} is
144 now legal as long as the string has the right length.)
148 Assignment of an object to a single target is recursively defined as
151 \begin{itemize
} % nested
154 If the target is an identifier (name):
159 If the name does not occur in a
\keyword{global
} statement in the current
160 code block: the name is bound to the object in the current local
165 Otherwise: the name is bound to the object in the current global
168 \end{itemize
} % nested
170 The name is rebound if it was already bound. This may cause the
171 reference count for the object previously bound to the name to reach
172 zero, causing the object to be deallocated and its
173 destructor
\index{destructor
} (if it has one) to be called.
176 If the target is a target list enclosed in parentheses or in square
177 brackets: The object must be a sequence with the same number of items
178 as there are targets in the target list, and its items are assigned,
179 from left to right, to the corresponding targets.
182 If the target is an attribute reference: The primary expression in the
183 reference is evaluated. It should yield an object with assignable
184 attributes; if this is not the case,
\exception{TypeError
} is raised. That
185 object is then asked to assign the assigned object to the given
186 attribute; if it cannot perform the assignment, it raises an exception
187 (usually but not necessarily
\exception{AttributeError
}).
188 \indexii{attribute
}{assignment
}
191 If the target is a subscription: The primary expression in the
192 reference is evaluated. It should yield either a mutable sequence
193 object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
194 the subscript expression is evaluated.
195 \indexii{subscription
}{assignment
}
198 If the primary is a mutable sequence object (e.g., a list), the subscript
199 must yield a plain integer. If it is negative, the sequence's length
200 is added to it. The resulting value must be a nonnegative integer
201 less than the sequence's length, and the sequence is asked to assign
202 the assigned object to its item with that index. If the index is out
203 of range,
\exception{IndexError
} is raised (assignment to a subscripted
204 sequence cannot add new items to a list).
208 If the primary is a mapping object (e.g., a dictionary), the subscript must
209 have a type compatible with the mapping's key type, and the mapping is
210 then asked to create a key/datum pair which maps the subscript to
211 the assigned object. This can either replace an existing key/value
212 pair with the same key value, or insert a new key/value pair (if no
213 key with the same value existed).
218 If the target is a slicing: The primary expression in the reference is
219 evaluated. It should yield a mutable sequence object (e.g., a list). The
220 assigned object should be a sequence object of the same type. Next,
221 the lower and upper bound expressions are evaluated, insofar they are
222 present; defaults are zero and the sequence's length. The bounds
223 should evaluate to (small) integers. If either bound is negative, the
224 sequence's length is added to it. The resulting bounds are clipped to
225 lie between zero and the sequence's length, inclusive. Finally, the
226 sequence object is asked to replace the slice with the items of the
227 assigned sequence. The length of the slice may be different from the
228 length of the assigned sequence, thus changing the length of the
229 target sequence, if the object allows it.
230 \indexii{slicing
}{assignment
}
234 (In the current implementation, the syntax for targets is taken
235 to be the same as for expressions, and invalid syntax is rejected
236 during the code generation phase, causing less detailed error
239 WARNING: Although the definition of assignment implies that overlaps
240 between the left-hand side and the right-hand side are `safe' (e.g.,
241 \samp{a, b = b, a
} swaps two variables), overlaps
\emph{within
} the
242 collection of assigned-to variables are not safe! For instance, the
243 following program prints
\samp{[0,
2]}:
253 \subsection{Augmented Assignment statements
\label{augassign
}}
255 Augmented assignment is the combination, in a single statement, of a binary
256 operation and an assignment statement:
257 \indexii{augmented
}{assignment
}
258 \index{statement!assignment, augmented
}
261 augmented_assignment_stmt: target augop expression_list
262 augop: "+=" | "-=" | "*=" | "/=" | "
%=" | "**="
263 | ">>=" | "<<=" | "&=" | "^=" | "|="
264 target: identifier | "(" target_list ")" | "
[" target_list "
]"
265 | attributeref | subscription | slicing
268 (See section
\ref{primaries
} for the syntax definitions for the last
271 An augmented assignment evaluates the target (which, unlike normal
272 assignment statements, cannot be an unpacking) and the expression
273 list, performs the binary operation specific to the type of assignment
274 on the two operands, and assigns the result to the original
275 target. The target is only evaluated once.
277 An augmented assignment expression like
\code{x +=
1} can be rewritten as
278 \code{x = x +
1} to achieve a similar, but not exactly equal effect. In the
279 augmented version,
\code{x
} is only evaluated once. Also, when possible, the
280 actual operation is performed
\emph{in-place
}, meaning that rather than
281 creating a new object and assigning that to the target, the old object is
284 With the exception of assigning to tuples and multiple targets in a single
285 statement, the assignment done by augmented assignment statements is handled
286 the same way as normal assignments. Similarly, with the exception of the
287 possible
\emph{in-place
} behaviour, the binary operation performed by
288 augmented assignment is the same as the normal binary operations.
291 \section{The
\keyword{pass
} statement
\label{pass
}}
298 \keyword{pass
} is a null operation --- when it is executed, nothing
299 happens. It is useful as a placeholder when a statement is
300 required syntactically, but no code needs to be executed, for example:
301 \indexii{null
}{operation
}
304 def f(arg): pass # a function that does nothing (yet)
306 class C: pass # a class with no methods (yet)
309 \section{The
\keyword{del
} statement
\label{del
}}
313 del_stmt: "del" target_list
316 Deletion is recursively defined very similar to the way assignment is
317 defined. Rather that spelling it out in full details, here are some
319 \indexii{deletion
}{target
}
320 \indexiii{deletion
}{target
}{list
}
322 Deletion of a target list recursively deletes each target, from left
325 Deletion of a name removes the binding of that name (which must exist)
326 from the local or global namespace, depending on whether the name
327 occurs in a
\keyword{global
} statement in the same code block.
329 \indexii{unbinding
}{name
}
331 Deletion of attribute references, subscriptions and slicings
332 is passed to the primary object involved; deletion of a slicing
333 is in general equivalent to assignment of an empty slice of the
334 right type (but even this is determined by the sliced object).
335 \indexii{attribute
}{deletion
}
337 \section{The
\keyword{print
} statement
\label{print
}}
341 print_stmt: "print"
[ expression ("," expression)*
[","
] ]
344 \keyword{print
} evaluates each expression in turn and writes the
345 resulting object to standard output (see below). If an object is not
346 a string, it is first converted to a string using the rules for string
347 conversions. The (resulting or original) string is then written. A
348 space is written before each object is (converted and) written, unless
349 the output system believes it is positioned at the beginning of a
350 line. This is the case (
1) when no characters have yet been written
351 to standard output, (
2) when the last character written to standard
352 output is
\character{\e n
}, or (
3) when the last write operation on
353 standard output was not a
\keyword{print
} statement. (In some cases
354 it may be functional to write an empty string to standard output for
357 \indexii{writing
}{values
}
359 A
\character{\e n
} character is written at the end, unless the
360 \keyword{print
} statement ends with a comma. This is the only action
361 if the statement contains just the keyword
\keyword{print
}.
362 \indexii{trailing
}{comma
}
363 \indexii{newline
}{suppression
}
365 Standard output is defined as the file object named
\code{stdout
}
366 in the built-in module
\module{sys
}. If no such object exists, or if
367 it does not have a
\method{write()
} method, a
\exception{RuntimeError
}
369 \indexii{standard
}{output
}
371 \withsubitem{(in module sys)
}{\ttindex{stdout
}}
372 \exindex{RuntimeError
}
374 \keyword{print
} also has an extended form, defined as
375 \index{extended print statement
}
378 print_stmt: "print" ">>" expression
[ ("," expression)+
[","
] ]
381 In this form, the first expression after the
\code{>
}\code{>
} must
382 evaluate to a ``file-like'' object, specifically an object that has a
383 \method{write()
} method as described above. With this extended form,
384 the subsequent expressions are printed to this file object. If the
385 first expression evaluates to
\code{None
}, then
\code{sys.stdout
} is
386 used as the file for output.
388 \section{The
\keyword{return
} statement
\label{return
}}
392 return_stmt: "return"
[expression_list
]
395 \keyword{return
} may only occur syntactically nested in a function
396 definition, not within a nested class definition.
397 \indexii{function
}{definition
}
398 \indexii{class
}{definition
}
400 If an expression list is present, it is evaluated, else
\code{None
}
403 \keyword{return
} leaves the current function call with the expression
404 list (or
\code{None
}) as return value.
406 When
\keyword{return
} passes control out of a
\keyword{try
} statement
407 with a
\keyword{finally
} clause, that
\keyword{finally
} clause is executed
408 before really leaving the function.
411 \section{The
\keyword{raise
} statement
\label{raise
}}
415 raise_stmt: "raise"
[expression
["," expression
["," expression
]]]
418 If no expressions are present,
\keyword{raise
} re-raises the last
419 expression that was raised in the current scope.
421 Otherwise,
\keyword{raise
} evaluates its first expression, which must yield
422 a string, class, or instance object. If there is a second expression,
423 this is evaluated, else
\code{None
} is substituted. If the first
424 expression is a class object, then the second expression may be an
425 instance of that class or one of its derivatives, and then that
426 instance is raised. If the second expression is not such an instance,
427 the given class is instantiated. The argument list for the
428 instantiation is determined as follows: if the second expression is a
429 tuple, it is used as the argument list; if it is
\code{None
}, the
430 argument list is empty; otherwise, the argument list consists of a
431 single argument which is the second expression. If the first
432 expression is an instance object, the second expression must be
435 \indexii{raising
}{exception
}
437 If the first object is a string, it then raises the exception
438 identified by the first object, with the second one (or
\code{None
})
439 as its parameter. If the first object is a class or instance,
440 it raises the exception identified by the class of the instance
441 determined in the previous step, with the instance as
444 If a third object is present, and it is not
\code{None
}, it should be
445 a traceback object (see section
\ref{traceback
}), and it is
446 substituted instead of the current location as the place where the
447 exception occurred. This is useful to re-raise an exception
448 transparently in an except clause.
451 \section{The
\keyword{break
} statement
\label{break
}}
458 \keyword{break
} may only occur syntactically nested in a
\keyword{for
}
459 or
\keyword{while
} loop, but not nested in a function or class definition
463 \indexii{loop
}{statement
}
465 It terminates the nearest enclosing loop, skipping the optional
466 \keyword{else
} clause if the loop has one.
469 If a
\keyword{for
} loop is terminated by
\keyword{break
}, the loop control
470 target keeps its current value.
471 \indexii{loop control
}{target
}
473 When
\keyword{break
} passes control out of a
\keyword{try
} statement
474 with a
\keyword{finally
} clause, that
\keyword{finally
} clause is executed
475 before really leaving the loop.
478 \section{The
\keyword{continue
} statement
\label{continue
}}
482 continue_stmt: "continue"
485 \keyword{continue
} may only occur syntactically nested in a
\keyword{for
} or
486 \keyword{while
} loop, but not nested in a function or class definition or
487 \keyword{try
} statement within that loop.
\footnote{It may
488 occur within an
\keyword{except
} or
\keyword{else
} clause. The
489 restriction on occurring in the
\keyword{try
} clause is implementor's
490 laziness and will eventually be lifted.
}
491 It continues with the next cycle of the nearest enclosing loop.
494 \indexii{loop
}{statement
}
497 \section{The
\keyword{import
} statement
\label{import
}}
501 import_stmt: "import" module
["as" name
] ("," module
["as" name
] )*
502 | "from" module "import" identifier
["as" name
]
503 ("," identifier
["as" name
] )*
504 | "from" module "import" "*"
505 module: (identifier ".")* identifier
508 Import statements are executed in two steps: (
1) find a module, and
509 initialize it if necessary; (
2) define a name or names in the local
510 namespace (of the scope where the
\keyword{import
} statement occurs).
511 The first form (without
\keyword{from
}) repeats these steps for each
512 identifier in the list. The form with
\keyword{from
} performs step
513 (
1) once, and then performs step (
2) repeatedly.
514 \indexii{importing
}{module
}
515 \indexii{name
}{binding
}
517 % XXX Need to define what ``initialize'' means here
519 The system maintains a table of modules that have been initialized,
520 indexed by module name. This table is
521 accessible as
\code{sys.modules
}. When a module name is found in
522 this table, step (
1) is finished. If not, a search for a module
523 definition is started. When a module is found, it is loaded. Details
524 of the module searching and loading process are implementation and
525 platform specific. It generally involves searching for a ``built-in''
526 module with the given name and then searching a list of locations
527 given as
\code{sys.path
}.
528 \withsubitem{(in module sys)
}{\ttindex{modules
}}
529 \ttindex{sys.modules
}
530 \indexii{module
}{name
}
531 \indexii{built-in
}{module
}
532 \indexii{user-defined
}{module
}
534 \indexii{filename
}{extension
}
535 \indexiii{module
}{search
}{path
}
537 If a built-in module is found, its built-in initialization code is
538 executed and step (
1) is finished. If no matching file is found,
539 \exception{ImportError
} is raised. If a file is found, it is parsed,
540 yielding an executable code block. If a syntax error occurs,
541 \exception{SyntaxError
} is raised. Otherwise, an empty module of the given
542 name is created and inserted in the module table, and then the code
543 block is executed in the context of this module. Exceptions during
544 this execution terminate step (
1).
545 \indexii{module
}{initialization
}
546 \exindex{SyntaxError
}
547 \exindex{ImportError
}
550 When step (
1) finishes without raising an exception, step (
2) can
553 The first form of
\keyword{import
} statement binds the module name in
554 the local namespace to the module object, and then goes on to import
555 the next identifier, if any. If the module name is followed by
556 \keyword{as
}, the name following
\keyword{as
} is used as the local
557 name for the module. To avoid confusion, you cannot import modules
558 with dotted names
\keyword{as
} a different local name. So
\code{import
559 module as m
} is legal, but
\code{import module.submod as s
} is not.
560 The latter should be written as
\code{from module import submod as s
};
563 The
\keyword{from
} form does not bind the module name: it goes through the
564 list of identifiers, looks each one of them up in the module found in step
565 (
1), and binds the name in the local namespace to the object thus found.
566 As with the first form of
\keyword{import
}, an alternate local name can be
567 supplied by specifying "
\keyword{as
} localname". If a name is not found,
568 \exception{ImportError
} is raised. If the list of identifiers is replaced
569 by a star (
\samp{*
}), all names defined in the module are bound, except
570 those beginning with an underscore (
\character{_
}).
571 \indexii{name
}{binding
}
572 \exindex{ImportError
}
574 Names bound by
\keyword{import
} statements may not occur in
575 \keyword{global
} statements in the same scope.
578 The
\keyword{from
} form with
\samp{*
} may only occur in a module scope.
582 \strong{Hierarchical module names:
}\indexiii{hierarchical
}{module
}{names
}
583 when the module names contains one or more dots, the module search
584 path is carried out differently. The sequence of identifiers up to
585 the last dot is used to find a ``package''
\index{packages
}; the final
586 identifier is then searched inside the package. A package is
587 generally a subdirectory of a directory on
\code{sys.path
} that has a
588 file
\file{__init__.py
}.
\ttindex{__init__.py
}
590 [XXX Can't be bothered to spell this out right now; see the URL
591 \url{http://www.python.org/doc/essays/packages.html
} for more details, also
592 about how the module search works from inside a package.
]
594 [XXX Also should mention __import__().
]
595 \bifuncindex{__import__
}
597 \section{The
\keyword{global
} statement
\label{global
}}
601 global_stmt: "global" identifier ("," identifier)*
604 The
\keyword{global
} statement is a declaration which holds for the
605 entire current code block. It means that the listed identifiers are to be
606 interpreted as globals. While
\emph{using
} global names is automatic
607 if they are not defined in the local scope,
\emph{assigning
} to global
608 names would be impossible without
\keyword{global
}.
609 \indexiii{global
}{name
}{binding
}
611 Names listed in a
\keyword{global
} statement must not be used in the same
612 code block textually preceding that
\keyword{global
} statement.
614 Names listed in a
\keyword{global
} statement must not be defined as formal
615 parameters or in a
\keyword{for
} loop control target,
\keyword{class
}
616 definition, function definition, or
\keyword{import
} statement.
618 (The current implementation does not enforce the latter two
619 restrictions, but programs should not abuse this freedom, as future
620 implementations may enforce them or silently change the meaning of the
623 \strong{Programmer's note:
}
624 the
\keyword{global
} is a directive to the parser. It
625 applies only to code parsed at the same time as the
\keyword{global
}
626 statement. In particular, a
\keyword{global
} statement contained in an
627 \keyword{exec
} statement does not affect the code block
\emph{containing
}
628 the
\keyword{exec
} statement, and code contained in an
\keyword{exec
}
629 statement is unaffected by
\keyword{global
} statements in the code
630 containing the
\keyword{exec
} statement. The same applies to the
631 \function{eval()
},
\function{execfile()
} and
\function{compile()
} functions.
634 \bifuncindex{execfile
}
635 \bifuncindex{compile
}
637 \section{The
\keyword{exec
} statement
\label{exec
}}
641 exec_stmt: "exec" expression
["in" expression
["," expression
]]
644 This statement supports dynamic execution of Python code. The first
645 expression should evaluate to either a string, an open file object, or
646 a code object. If it is a string, the string is parsed as a suite of
647 Python statements which is then executed (unless a syntax error
648 occurs). If it is an open file, the file is parsed until EOF and
649 executed. If it is a code object, it is simply executed.
651 In all cases, if the optional parts are omitted, the code is executed
652 in the current scope. If only the first expression after
\keyword{in
}
653 is specified, it should be a dictionary, which will be used for both
654 the global and the local variables. If two expressions are given,
655 both must be dictionaries and they are used for the global and local
656 variables, respectively.
658 As a side effect, an implementation may insert additional keys into
659 the dictionaries given besides those corresponding to variable names
660 set by the executed code. For example, the current implementation
661 may add a reference to the dictionary of the built-in module
662 \module{__builtin__
} under the key
\code{__builtins__
} (!).
663 \ttindex{__builtins__
}
664 \refbimodindex{__builtin__
}
666 \strong{Programmer's hints:
}
667 dynamic evaluation of expressions is supported by the built-in
668 function
\function{eval()
}. The built-in functions
669 \function{globals()
} and
\function{locals()
} return the current global
670 and local dictionary, respectively, which may be useful to pass around
671 for use by
\keyword{exec
}.
673 \bifuncindex{globals
}
676 Also, in the current implementation, multi-line compound statements must
678 \code{exec "for v in seq:
\e{}n
\e{}tprint v
\e{}n"
} works, but
679 \code{exec "for v in seq:
\e{}n
\e{}tprint v"
} fails with
680 \exception{SyntaxError
}.
681 \exindex{SyntaxError
}