928 lines · 36.5 KB · TeX
RawDownload
\chapter{Simple statements \label{simple}}\indexii{simple}{statement} Simple statements are comprised within a single logical line.Several simple statements may occur on a single line separatedby semicolons.  The syntax for simple statements is: \begin{productionlist}  \production{simple_stmt}{\token{expression_stmt}}  \productioncont{| \token{assert_stmt}}  \productioncont{| \token{assignment_stmt}}  \productioncont{| \token{augmented_assignment_stmt}}  \productioncont{| \token{pass_stmt}}  \productioncont{| \token{del_stmt}}  \productioncont{| \token{print_stmt}}  \productioncont{| \token{return_stmt}}  \productioncont{| \token{yield_stmt}}  \productioncont{| \token{raise_stmt}}  \productioncont{| \token{break_stmt}}  \productioncont{| \token{continue_stmt}}  \productioncont{| \token{import_stmt}}  \productioncont{| \token{global_stmt}}  \productioncont{| \token{exec_stmt}}\end{productionlist}  \section{Expression statements \label{exprstmts}}\indexii{expression}{statement} Expression statements are used (mostly interactively) to compute andwrite a value, or (usually) to call a procedure (a function thatreturns no meaningful result; in Python, procedures return the value\code{None}).  Other uses of expression statements are allowed andoccasionally useful.  The syntax for an expression statement is: \begin{productionlist}  \production{expression_stmt}             {\token{expression_list}}\end{productionlist} An expression statement evaluates the expression list (which may be asingle expression).\indexii{expression}{list} In interactive mode, if the value is not \code{None}, it is convertedto a string using the built-in \function{repr()}\bifuncindex{repr}function and the resulting string is written to standard output (seesection~\ref{print}) on a line by itself.  (Expression statementsyielding \code{None} are not written, so that procedure calls do notcause any output.)\obindex{None}\indexii{string}{conversion}\index{output}\indexii{standard}{output}\indexii{writing}{values}\indexii{procedure}{call}  \section{Assert statements \label{assert}} Assert statements\stindex{assert} are a convenient way to insertdebugging assertions\indexii{debugging}{assertions} into a program: \begin{productionlist}  \production{assert_stmt}             {"assert" \token{expression} ["," \token{expression}]}\end{productionlist} The simple form, \samp{assert expression}, is equivalent to \begin{verbatim}if __debug__:   if not expression: raise AssertionError\end{verbatim} The extended form, \samp{assert expression1, expression2}, isequivalent to \begin{verbatim}if __debug__:   if not expression1: raise AssertionError, expression2\end{verbatim} These equivalences assume that \code{__debug__}\ttindex{__debug__} and\exception{AssertionError}\exindex{AssertionError} refer to the built-invariables with those names.  In the current implementation, thebuilt-in variable \code{__debug__} is \code{True} under normalcircumstances, \code{False} when optimization is requested (command lineoption -O).  The current code generator emits no code for an assertstatement when optimization is requested at compile time.  Note that itis unnecessary to include the source code for the expression that failedin the error message;it will be displayed as part of the stack trace. Assignments to \code{__debug__} are illegal.  The value for thebuilt-in variable is determined when the interpreter starts.  \section{Assignment statements \label{assignment}} Assignment statements\indexii{assignment}{statement} are used to(re)bind names to values and to modify attributes or items of mutableobjects:\indexii{binding}{name}\indexii{rebinding}{name}\obindex{mutable}\indexii{attribute}{assignment} \begin{productionlist}  \production{assignment_stmt}             {(\token{target_list} "=")+              (\token{expression_list} | \token{yield_expression})}  \production{target_list}             {\token{target} ("," \token{target})* [","]}  \production{target}             {\token{identifier}}  \productioncont{| "(" \token{target_list} ")"}  \productioncont{| "[" \token{target_list} "]"}  \productioncont{| \token{attributeref}}  \productioncont{| \token{subscription}}  \productioncont{| \token{slicing}}\end{productionlist} (See section~\ref{primaries} for the syntax definitions for the lastthree symbols.) An assignment statement evaluates the expression list (remember thatthis can be a single expression or a comma-separated list, the latteryielding a tuple) and assigns the single resulting object to each ofthe target lists, from left to right.\indexii{expression}{list} Assignment is defined recursively depending on the form of the target(list).  When a target is part of a mutable object (an attributereference, subscription or slicing), the mutable object mustultimately perform the assignment and decide about its validity, andmay raise an exception if the assignment is unacceptable.  The rulesobserved by various types and the exceptions raised are given with thedefinition of the object types (see section~\ref{types}).\index{target}\indexii{target}{list} Assignment of an object to a target list is recursively defined asfollows.\indexiii{target}{list}{assignment} \begin{itemize}\itemIf the target list is a single target: The object is assigned to thattarget. \itemIf the target list is a comma-separated list of targets: The objectmust be a sequence with the same number of items as there aretargets in the target list, and the items are assigned, from left toright, to the corresponding targets.  (This rule is relaxed as ofPython 1.5; in earlier versions, the object had to be a tuple.  Sincestrings are sequences, an assignment like \samp{a, b = "xy"} isnow legal as long as the string has the right length.) \end{itemize} Assignment of an object to a single target is recursively defined asfollows. \begin{itemize} % nested \itemIf the target is an identifier (name): \begin{itemize} \itemIf the name does not occur in a \keyword{global} statement in the currentcode block: the name is bound to the object in the current localnamespace.\stindex{global} \itemOtherwise: the name is bound to the object in the current globalnamespace. \end{itemize} % nested The name is rebound if it was already bound.  This may cause thereference count for the object previously bound to the name to reachzero, causing the object to be deallocated and itsdestructor\index{destructor} (if it has one) to be called. \itemIf the target is a target list enclosed in parentheses or in squarebrackets: The object must be a sequence with the same number of itemsas there are targets in the target list, and its items are assigned,from left to right, to the corresponding targets. \itemIf the target is an attribute reference: The primary expression in thereference is evaluated.  It should yield an object with assignableattributes; if this is not the case, \exception{TypeError} is raised.  Thatobject is then asked to assign the assigned object to the givenattribute; if it cannot perform the assignment, it raises an exception(usually but not necessarily \exception{AttributeError}).\indexii{attribute}{assignment} \itemIf the target is a subscription: The primary expression in thereference is evaluated.  It should yield either a mutable sequenceobject (such as a list) or a mapping object (such as a dictionary). Next,the subscript expression is evaluated.\indexii{subscription}{assignment}\obindex{mutable} If the primary is a mutable sequence object (such as a list), the subscriptmust yield a plain integer.  If it is negative, the sequence's lengthis added to it.  The resulting value must be a nonnegative integerless than the sequence's length, and the sequence is asked to assignthe assigned object to its item with that index.  If the index is outof range, \exception{IndexError} is raised (assignment to a subscriptedsequence cannot add new items to a list).\obindex{sequence}\obindex{list} If the primary is a mapping object (such as a dictionary), the subscript musthave a type compatible with the mapping's key type, and the mapping isthen asked to create a key/datum pair which maps the subscript tothe assigned object.  This can either replace an existing key/valuepair with the same key value, or insert a new key/value pair (if nokey with the same value existed).\obindex{mapping}\obindex{dictionary} \itemIf the target is a slicing: The primary expression in the reference isevaluated.  It should yield a mutable sequence object (such as a list).  Theassigned object should be a sequence object of the same type.  Next,the lower and upper bound expressions are evaluated, insofar they arepresent; defaults are zero and the sequence's length.  The boundsshould evaluate to (small) integers.  If either bound is negative, thesequence's length is added to it.  The resulting bounds are clipped tolie between zero and the sequence's length, inclusive.  Finally, thesequence object is asked to replace the slice with the items of theassigned sequence.  The length of the slice may be different from thelength of the assigned sequence, thus changing the length of thetarget sequence, if the object allows it.\indexii{slicing}{assignment} \end{itemize}        (In the current implementation, the syntax for targets is takento be the same as for expressions, and invalid syntax is rejectedduring the code generation phase, causing less detailed errormessages.) WARNING: Although the definition of assignment implies that overlapsbetween the left-hand side and the right-hand side are `safe' (for example\samp{a, b = b, a} swaps two variables), overlaps \emph{within} thecollection of assigned-to variables are not safe!  For instance, thefollowing program prints \samp{[0, 2]}: \begin{verbatim}x = [0, 1]i = 0i, x[i] = 1, 2print x\end{verbatim}  \subsection{Augmented assignment statements \label{augassign}} Augmented assignment is the combination, in a single statement, of a binaryoperation and an assignment statement:\indexii{augmented}{assignment}\index{statement!assignment, augmented} \begin{productionlist}  \production{augmented_assignment_stmt}             {\token{target} \token{augop}              (\token{expression_list} | \token{yield_expression})}  \production{augop}             {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="}  \productioncont{| ">>=" | "<<=" | "\&=" | "\textasciicircum=" | "|="}\end{productionlist} (See section~\ref{primaries} for the syntax definitions for the lastthree symbols.) An augmented assignment evaluates the target (which, unlike normalassignment statements, cannot be an unpacking) and the expressionlist, performs the binary operation specific to the type of assignmenton the two operands, and assigns the result to the originaltarget.  The target is only evaluated once. An augmented assignment expression like \code{x += 1} can be rewritten as\code{x = x + 1} to achieve a similar, but not exactly equal effect. In theaugmented version, \code{x} is only evaluated once. Also, when possible, theactual operation is performed \emph{in-place}, meaning that rather thancreating a new object and assigning that to the target, the old object ismodified instead. With the exception of assigning to tuples and multiple targets in a singlestatement, the assignment done by augmented assignment statements is handledthe same way as normal assignments. Similarly, with the exception of thepossible \emph{in-place} behavior, the binary operation performed byaugmented assignment is the same as the normal binary operations. For targets which are attribute references, the initial value isretrieved with a \method{getattr()} and the result is assigned with a\method{setattr()}.  Notice that the two methods do not necessarilyrefer to the same variable.  When \method{getattr()} refers to a classvariable, \method{setattr()} still writes to an instance variable.For example: \begin{verbatim}class A:    x = 3    # class variablea = A()a.x += 1     # writes a.x as 4 leaving A.x as 3\end{verbatim}  \section{The \keyword{pass} statement \label{pass}}\stindex{pass} \begin{productionlist}  \production{pass_stmt}             {"pass"}\end{productionlist} \keyword{pass} is a null operation --- when it is executed, nothinghappens.  It is useful as a placeholder when a statement isrequired syntactically, but no code needs to be executed, for example:\indexii{null}{operation} \begin{verbatim}def f(arg): pass    # a function that does nothing (yet) class C: pass       # a class with no methods (yet)\end{verbatim}  \section{The \keyword{del} statement \label{del}}\stindex{del} \begin{productionlist}  \production{del_stmt}             {"del" \token{target_list}}\end{productionlist} Deletion is recursively defined very similar to the way assignment isdefined. Rather that spelling it out in full details, here are somehints.\indexii{deletion}{target}\indexiii{deletion}{target}{list} Deletion of a target list recursively deletes each target, from leftto right. Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the nameoccurs in a \keyword{global} statement in the same code block.  If thename is unbound, a \exception{NameError} exception will be raised.\stindex{global}\indexii{unbinding}{name} It is illegal to delete a name from the local namespace if it occursas a free variable\indexii{free}{variable} in a nested block. Deletion of attribute references, subscriptions and slicingsis passed to the primary object involved; deletion of a slicingis in general equivalent to assignment of an empty slice of theright type (but even this is determined by the sliced object).\indexii{attribute}{deletion}  \section{The \keyword{print} statement \label{print}}\stindex{print} \begin{productionlist}  \production{print_stmt}             {"print" ([\token{expression} ("," \token{expression})* [","]}  \productioncont{| ">>" \token{expression}                  [("," \token{expression})+ [","])}\end{productionlist} \keyword{print} evaluates each expression in turn and writes theresulting object to standard output (see below).  If an object is nota string, it is first converted to a string using the rules for stringconversions.  The (resulting or original) string is then written.  Aspace is written before each object is (converted and) written, unlessthe output system believes it is positioned at the beginning of aline.  This is the case (1) when no characters have yet been writtento standard output, (2) when the last character written to standardoutput is \character{\e n}, or (3) when the last write operation onstandard output was not a \keyword{print} statement.  (In some casesit may be functional to write an empty string to standard output forthis reason.)  \note{Objects which act like file objects but which arenot the built-in file objects often do not properly emulate thisaspect of the file object's behavior, so it is best not to rely onthis.}\index{output}\indexii{writing}{values} A \character{\e n} character is written at the end, unless the\keyword{print} statement ends with a comma.  This is the only actionif the statement contains just the keyword \keyword{print}.\indexii{trailing}{comma}\indexii{newline}{suppression} Standard output is defined as the file object named \code{stdout}in the built-in module \module{sys}.  If no such object exists, or ifit does not have a \method{write()} method, a \exception{RuntimeError}exception is raised.\indexii{standard}{output}\refbimodindex{sys}\withsubitem{(in module sys)}{\ttindex{stdout}}\exindex{RuntimeError} \keyword{print} also has an extended\index{extended print statement}form, defined by the second portion of the syntax described above.This form is sometimes referred to as ``\keyword{print} chevron.''In this form, the first expression after the \code{>>} mustevaluate to a ``file-like'' object, specifically an object that has a\method{write()} method as described above.  With this extended form,the subsequent expressions are printed to this file object.  If thefirst expression evaluates to \code{None}, then \code{sys.stdout} isused as the file for output.  \section{The \keyword{return} statement \label{return}}\stindex{return} \begin{productionlist}  \production{return_stmt}             {"return" [\token{expression_list}]}\end{productionlist} \keyword{return} may only occur syntactically nested in a functiondefinition, not within a nested class definition.\indexii{function}{definition}\indexii{class}{definition} If an expression list is present, it is evaluated, else \code{None}is substituted. \keyword{return} leaves the current function call with the expressionlist (or \code{None}) as return value. When \keyword{return} passes control out of a \keyword{try} statementwith a \keyword{finally} clause, that \keyword{finally} clause is executedbefore really leaving the function.\kwindex{finally} In a generator function, the \keyword{return} statement is not allowedto include an \grammartoken{expression_list}.  In that context, a bare\keyword{return} indicates that the generator is done and will cause\exception{StopIteration} to be raised.  \section{The \keyword{yield} statement \label{yield}}\stindex{yield} \begin{productionlist}  \production{yield_stmt}             {\token{yield_expression}}\end{productionlist} \index{generator!function}\index{generator!iterator}\index{function!generator}\exindex{StopIteration} The \keyword{yield} statement is only used when defining a generatorfunction, and is only used in the body of the generator function.Using a \keyword{yield} statement in a function definition issufficient to cause that definition to create a generator functioninstead of a normal function. When a generator function is called, it returns an iterator known as agenerator iterator, or more commonly, a generator.  The body of thegenerator function is executed by calling the generator's\method{next()} method repeatedly until it raises an exception. When a \keyword{yield} statement is executed, the state of thegenerator is frozen and the value of \grammartoken{expression_list} isreturned to \method{next()}'s caller.  By ``frozen'' we mean that alllocal state is retained, including the current bindings of localvariables, the instruction pointer, and the internal evaluation stack:enough information is saved so that the next time \method{next()} isinvoked, the function can proceed exactly as if the \keyword{yield}statement were just another external call. As of Python version 2.5, the \keyword{yield} statement is nowallowed in the \keyword{try} clause of a \keyword{try} ...\ \keyword{finally} construct.  If the generator is not resumed beforeit is finalized (by reaching a zero reference count or by being garbagecollected), the generator-iterator's \method{close()} method will becalled, allowing any pending \keyword{finally} clauses to execute. \begin{notice}In Python 2.2, the \keyword{yield} statement is only allowed

Lines 1–500 of 928.