cinap_lenrekadd hg and python4bb9e2215 years agoHistory
1325 lines · 52.2 KB · TeX
RawDownload
\chapter{Expressions\label{expressions}}\index{expression} This chapter explains the meaning of the elements of expressions inPython. \strong{Syntax Notes:} In this and the following chapters, extendedBNF\index{BNF} notation will be used to describe syntax, not lexicalanalysis.  When (one alternative of) a syntax rule has the form \begin{productionlist}[*]  \production{name}{\token{othername}}\end{productionlist} and no semantics are given, the semantics of this form of \code{name}are the same as for \code{othername}.\index{syntax}  \section{Arithmetic conversions\label{conversions}}\indexii{arithmetic}{conversion} When a description of an arithmetic operator below uses the phrase``the numeric arguments are converted to a common type,'' thearguments are coerced using the coercion rules listed at~\ref{coercion-rules}.  If both arguments are standard numeric types,the following coercions are applied: \begin{itemize}\item	If either argument is a complex number, the other is converted	to complex;\item	otherwise, if either argument is a floating point number,	the other is converted to floating point;\item	otherwise, if either argument is a long integer,	the other is converted to long integer;\item	otherwise, both must be plain integers and no conversion	is necessary.\end{itemize} Some additional rules apply for certain operators (e.g., a string leftargument to the `\%' operator). Extensions can define their owncoercions.  \section{Atoms\label{atoms}}\index{atom} Atoms are the most basic elements of expressions.  The simplest atomsare identifiers or literals.  Forms enclosed inreverse quotes or in parentheses, brackets or braces are alsocategorized syntactically as atoms.  The syntax for atoms is: \begin{productionlist}  \production{atom}             {\token{identifier} | \token{literal} | \token{enclosure}}  \production{enclosure}             {\token{parenth_form} | \token{list_display}}  \productioncont{| \token{generator_expression} | \token{dict_display}}  \productioncont{| \token{string_conversion} | \token{yield_atom}}\end{productionlist}  \subsection{Identifiers (Names)\label{atom-identifiers}}\index{name}\index{identifier} An identifier occurring as an atom is a name.  Seesection \ref{identifiers} for lexical definition andsection~\ref{naming} for documentation of naming and binding. When the name is bound to an object, evaluation of the atom yieldsthat object.  When a name is not bound, an attempt to evaluate itraises a \exception{NameError} exception.\exindex{NameError} \strong{Private name mangling:}\indexii{name}{mangling}%\indexii{private}{names}%When an identifier that textually occurs in a class definition beginswith two or more underscore characters and does not end in two or moreunderscores, it is considered a \dfn{private name} of that class.Private names are transformed to a longer form before code isgenerated for them.  The transformation inserts the class name infront of the name, with leading underscores removed, and a singleunderscore inserted in front of the class name.  For example, theidentifier \code{__spam} occurring in a class named \code{Ham} will betransformed to \code{_Ham__spam}.  This transformation is independentof the syntactical context in which the identifier is used.  If thetransformed name is extremely long (longer than 255 characters),implementation defined truncation may happen.  If the class nameconsists only of underscores, no transformation is done.  \subsection{Literals\label{atom-literals}}\index{literal} Python supports string literals and various numeric literals: \begin{productionlist}  \production{literal}             {\token{stringliteral} | \token{integer} | \token{longinteger}}  \productioncont{| \token{floatnumber} | \token{imagnumber}}\end{productionlist} Evaluation of a literal yields an object of the given type (string,integer, long integer, floating point number, complex number) with thegiven value.  The value may be approximated in the case of floatingpoint and imaginary (complex) literals.  See section \ref{literals}for details. All literals correspond to immutable data types, and hence theobject's identity is less important than its value.  Multipleevaluations of literals with the same value (either the sameoccurrence in the program text or a different occurrence) may obtainthe same object or a different object with the same value.\indexiii{immutable}{data}{type}\indexii{immutable}{object}  \subsection{Parenthesized forms\label{parenthesized}}\index{parenthesized form} A parenthesized form is an optional expression list enclosed inparentheses: \begin{productionlist}  \production{parenth_form}             {"(" [\token{expression_list}] ")"}\end{productionlist} A parenthesized expression list yields whatever that expression listyields: if the list contains at least one comma, it yields a tuple;otherwise, it yields the single expression that makes up theexpression list. An empty pair of parentheses yields an empty tuple object.  Sincetuples are immutable, the rules for literals apply (i.e., twooccurrences of the empty tuple may or may not yield the same object).\indexii{empty}{tuple} Note that tuples are not formed by the parentheses, but rather by useof the comma operator.  The exception is the empty tuple, for whichparentheses \emph{are} required --- allowing unparenthesized ``nothing''in expressions would cause ambiguities and allow common typos topass uncaught.\index{comma}\indexii{tuple}{display}  \subsection{List displays\label{lists}}\indexii{list}{display}\indexii{list}{comprehensions} A list display is a possibly empty series of expressions enclosed insquare brackets: \begin{productionlist}  \production{list_display}             {"[" [\token{expression_list} | \token{list_comprehension}] "]"}  \production{list_comprehension}             {\token{expression} \token{list_for}}  \production{list_for}             {"for" \token{target_list} "in" \token{old_expression_list}              [\token{list_iter}]}  \production{old_expression_list}             {\token{old_expression}              [("," \token{old_expression})+ [","]]}  \production{list_iter}             {\token{list_for} | \token{list_if}}  \production{list_if}             {"if" \token{old_expression} [\token{list_iter}]}\end{productionlist} A list display yields a new list object.  Its contents are specifiedby providing either a list of expressions or a list comprehension.\indexii{list}{comprehensions}When a comma-separated list of expressions is supplied, its elements areevaluated from left to right and placed into the list object in thatorder.  When a list comprehension is supplied, it consists of asingle expression followed by at least one \keyword{for} clause and zero ormore \keyword{for} or \keyword{if} clauses.  In thiscase, the elements of the new list are those that would be producedby considering each of the \keyword{for} or \keyword{if} clauses a block,nesting fromleft to right, and evaluating the expression to produce a list elementeach time the innermost block is reached\footnote{In Python 2.3, alist comprehension "leaks" the control variables of each\samp{for} it contains into the containing scope.  However, thisbehavior is deprecated, and relying on it will not work once thisbug is fixed in a future release}.\obindex{list}\indexii{empty}{list}  \subsection{Generator expressions\label{genexpr}}\indexii{generator}{expression} A generator expression is a compact generator notation in parentheses: \begin{productionlist}  \production{generator_expression}             {"(" \token{expression} \token{genexpr_for} ")"}  \production{genexpr_for}             {"for" \token{target_list} "in" \token{or_test}              [\token{genexpr_iter}]}  \production{genexpr_iter}             {\token{genexpr_for} | \token{genexpr_if}}  \production{genexpr_if}             {"if" \token{old_expression} [\token{genexpr_iter}]}\end{productionlist} A generator expression yields a new generator object.\obindex{generator}It consists of a single expression followed by at least one\keyword{for} clause and zero or more \keyword{for} or \keyword{if}clauses.  The iterating values of the new generator are those thatwould be produced by considering each of the \keyword{for} or\keyword{if} clauses a block, nesting from left to right, andevaluating the expression to yield a value that is reached theinnermost block for each iteration. Variables used in the generator expression are evaluated lazilywhen the \method{next()} method is called for generator object(in the same fashion as normal generators). However, the leftmost\keyword{for} clause is immediately evaluated so that error producedby it can be seen before any other possible error in the code thathandles the generator expression.Subsequent \keyword{for} clauses cannot be evaluated immediately sincethey may depend on the previous \keyword{for} loop.For example: \samp{(x*y for x in range(10) for y in bar(x))}. The parentheses can be omitted on calls with only one argument.See section \ref{calls} for the detail.  \subsection{Dictionary displays\label{dict}}\indexii{dictionary}{display} A dictionary display is a possibly empty series of key/datum pairsenclosed in curly braces:\index{key}\index{datum}\index{key/datum pair} \begin{productionlist}  \production{dict_display}             {"\{" [\token{key_datum_list}] "\}"}  \production{key_datum_list}             {\token{key_datum} ("," \token{key_datum})* [","]}  \production{key_datum}             {\token{expression} ":" \token{expression}}\end{productionlist} A dictionary display yields a new dictionary object.\obindex{dictionary} The key/datum pairs are evaluated from left to right to define theentries of the dictionary: each key object is used as a key into thedictionary to store the corresponding datum. Restrictions on the types of the key values are listed earlier insection \ref{types}.  (To summarize, the key type should be hashable,which excludes all mutable objects.)  Clashes between duplicate keysare not detected; the last datum (textually rightmost in the display)stored for a given key value prevails.\indexii{immutable}{object}  \subsection{String conversions\label{string-conversions}}\indexii{string}{conversion}\indexii{reverse}{quotes}\indexii{backward}{quotes}\index{back-quotes} A string conversion is an expression list enclosed in reverse (a.k.a.backward) quotes: \begin{productionlist}  \production{string_conversion}             {"`" \token{expression_list} "`"}\end{productionlist} A string conversion evaluates the contained expression list andconverts the resulting object into a string according to rulesspecific to its type. If the object is a string, a number, \code{None}, or a tuple, list ordictionary containing only objects whose type is one of these, theresulting string is a valid Python expression which can be passed tothe built-in function \function{eval()} to yield an expression with thesame value (or an approximation, if floating point numbers areinvolved). (In particular, converting a string adds quotes around it and converts``funny'' characters to escape sequences that are safe to print.) Recursive objects (for example, lists or dictionaries that contain areference to themselves, directly or indirectly) use \samp{...} toindicate a recursive reference, and the result cannot be passed to\function{eval()} to get an equal value (\exception{SyntaxError} willbe raised instead).\obindex{recursive} The built-in function \function{repr()} performs exactly the sameconversion in its argument as enclosing it in parentheses and reversequotes does.  The built-in function \function{str()} performs asimilar but more user-friendly conversion.\bifuncindex{repr}\bifuncindex{str}  \subsection{Yield expressions\label{yieldexpr}}\kwindex{yield}\indexii{yield}{expression}\indexii{generator}{function} \begin{productionlist}  \production{yield_atom}             {"(" \token{yield_expression} ")"}  \production{yield_expression}             {"yield" [\token{expression_list}]}\end{productionlist} \versionadded{2.5} The \keyword{yield} expression is only used when defining a generatorfunction, and can only be used in the body of a function definition.Using a \keyword{yield} expression 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.  That generator then controls the execution of a generatorfunction.  The execution starts when one of the generator's methods iscalled.  At that time, the execution proceeds to the first\keyword{yield} expression, where it is suspended again, returning thevalue of \grammartoken{expression_list} to generator's caller.  Bysuspended we mean that all local state is retained, including thecurrent bindings of local variables, the instruction pointer, and theinternal evaluation stack.  When the execution is resumed by callingone of the generator's methods, the function can proceed exactly asif the \keyword{yield} expression was just another external call.The value of the \keyword{yield} expression after resuming depends onthe method which resumed the execution. \index{coroutine} All of this makes generator functions quite similar to coroutines; theyyield multiple times, they have more than one entry point and theirexecution can be suspended.  The only difference is that a generatorfunction cannot control where should the execution continue after ityields; the control is always transfered to the generator's caller. \obindex{generator} The following generator's methods can be used to control the executionof a generator function: \exindex{StopIteration} \begin{methoddesc}[generator]{next}{}  Starts the execution of a generator function or resumes it at the  last executed \keyword{yield} expression.  When a generator function  is resumed with a \method{next()} method, the current \keyword{yield}  expression always evaluates to \constant{None}.  The execution then  continues to the next \keyword{yield} expression, where the generator  is suspended again, and the value of the  \grammartoken{expression_list} is returned to \method{next()}'s  caller. If the generator exits without yielding another value, a  \exception{StopIteration} exception is raised.\end{methoddesc} \begin{methoddesc}[generator]{send}{value}  Resumes the execution and ``sends'' a value into the generator  function.  The \code{value} argument becomes the result of the  current \keyword{yield} expression.  The \method{send()} method  returns the next value yielded by the generator, or raises  \exception{StopIteration} if the generator exits without yielding  another value.  When \method{send()} is called to start the generator, it must be  called with \constant{None} as the argument, because there is no  \keyword{yield} expression that could receieve the value.\end{methoddesc} \begin{methoddesc}[generator]{throw}                  {type\optional{, value\optional{, traceback}}}  Raises an exception of type \code{type} at the point where generator  was paused, and returns the next value yielded by the generator  function.  If the generator exits without yielding another value, a  \exception{StopIteration} exception is raised.  If the generator  function does not catch the passed-in exception, or raises a  different exception, then that exception propagates to the caller.\end{methoddesc} \exindex{GeneratorExit} \begin{methoddesc}[generator]{close}{}  Raises a \exception{GeneratorExit} at the point where the generator  function was paused.  If the generator function then raises  \exception{StopIteration} (by exiting normally, or due to already  being closed) or \exception{GeneratorExit} (by not catching the  exception), close returns to its caller.  If the generator yields a  value, a \exception{RuntimeError} is raised.  If the generator raises  any other exception, it is propagated to the caller.  \method{close}  does nothing if the generator has already exited due to an exception  or normal exit.\end{methoddesc} Here is a simple example that demonstrates the behavior of generatorsand generator functions: \begin{verbatim}>>> def echo(value=None):...     print "Execution starts when 'next()' is called for the first time."...     try:...         while True:...             try:...                 value = (yield value)...             except GeneratorExit:...                 # never catch GeneratorExit...                 raise...             except Exception, e:...                 value = e...     finally:...         print "Don't forget to clean up when 'close()' is called."...>>> generator = echo(1)>>> print generator.next()Execution starts when 'next()' is called for the first time.1>>> print generator.next()None>>> print generator.send(2)2>>> generator.throw(TypeError, "spam")TypeError('spam',)>>> generator.close()Don't forget to clean up when 'close()' is called.\end{verbatim} \begin{seealso}  \seepep{0342}{Coroutines via Enhanced Generators}         {The proposal to enhance the API and syntax of generators,          making them usable as simple coroutines.}\end{seealso}  \section{Primaries\label{primaries}}\index{primary} Primaries represent the most tightly bound operations of the language.Their syntax is: \begin{productionlist}  \production{primary}             {\token{atom} | \token{attributeref}              | \token{subscription} | \token{slicing} | \token{call}}\end{productionlist}  \subsection{Attribute references\label{attribute-references}}\indexii{attribute}{reference} An attribute reference is a primary followed by a period and a name: \begin{productionlist}  \production{attributeref}             {\token{primary} "." \token{identifier}}\end{productionlist} The primary must evaluate to an object of a type that supportsattribute references, e.g., a module, list, or an instance.  Thisobject is then asked to produce the attribute whose name is theidentifier.  If this attribute is not available, the exception\exception{AttributeError}\exindex{AttributeError} is raised.Otherwise, the type and value of the object produced is determined bythe object.  Multiple evaluations of the same attribute reference mayyield different objects.\obindex{module}\obindex{list}  \subsection{Subscriptions\label{subscriptions}}\index{subscription} A subscription selects an item of a sequence (string, tuple or list)or mapping (dictionary) object:\obindex{sequence}\obindex{mapping}\obindex{string}\obindex{tuple}\obindex{list}\obindex{dictionary}\indexii{sequence}{item} \begin{productionlist}  \production{subscription}             {\token{primary} "[" \token{expression_list} "]"}\end{productionlist} 

Lines 1–500 of 1325.