blob: 5002f4d7fbe51fad9e3a28f9abc80cd61c86ca87 [file] [log] [blame]
Fred Drake020f8c01998-07-28 19:32:59 +00001\chapter{Expressions\label{expressions}}
Fred Drakef6669171998-05-06 19:52:49 +00002\index{expression}
Fred Drakef6669171998-05-06 19:52:49 +00003
Guido van Rossum3a0ad601998-07-23 21:57:42 +00004This chapter explains the meaning of the elements of expressions in
5Python.
Fred Drakef6669171998-05-06 19:52:49 +00006
Guido van Rossum3a0ad601998-07-23 21:57:42 +00007\strong{Syntax Notes:} In this and the following chapters, extended
8BNF\index{BNF} notation will be used to describe syntax, not lexical
9analysis. When (one alternative of) a syntax rule has the form
Fred Drakef6669171998-05-06 19:52:49 +000010
Fred Drakecb4638a2001-07-06 22:49:53 +000011\begin{productionlist}[*]
12 \production{name}{\token{othername}}
13\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000014
Fred Drake5c07d9b1998-05-14 19:37:06 +000015and no semantics are given, the semantics of this form of \code{name}
16are the same as for \code{othername}.
Fred Drakef6669171998-05-06 19:52:49 +000017\index{syntax}
18
Fred Drake2829f1c2001-06-23 05:27:20 +000019
Fred Drake020f8c01998-07-28 19:32:59 +000020\section{Arithmetic conversions\label{conversions}}
Fred Drakef6669171998-05-06 19:52:49 +000021\indexii{arithmetic}{conversion}
22
23When a description of an arithmetic operator below uses the phrase
Guido van Rossum3a0ad601998-07-23 21:57:42 +000024``the numeric arguments are converted to a common type,'' the
25arguments are coerced using the coercion rules listed at the end of
Fred Drakededa9f32001-06-23 06:06:21 +000026chapter \ref{datamodel}. If both arguments are standard numeric
27types, the following coercions are applied:
Fred Drakef6669171998-05-06 19:52:49 +000028
29\begin{itemize}
Guido van Rossum3a0ad601998-07-23 21:57:42 +000030\item If either argument is a complex number, the other is converted
31 to complex;
32\item otherwise, if either argument is a floating point number,
Fred Drakef6669171998-05-06 19:52:49 +000033 the other is converted to floating point;
Guido van Rossum3a0ad601998-07-23 21:57:42 +000034\item otherwise, if either argument is a long integer,
Fred Drakef6669171998-05-06 19:52:49 +000035 the other is converted to long integer;
36\item otherwise, both must be plain integers and no conversion
37 is necessary.
38\end{itemize}
39
Guido van Rossum7c0240f1998-07-24 15:36:43 +000040Some additional rules apply for certain operators (e.g., a string left
Guido van Rossum3a0ad601998-07-23 21:57:42 +000041argument to the `\%' operator). Extensions can define their own
42coercions.
Fred Drake020f8c01998-07-28 19:32:59 +000043
44
45\section{Atoms\label{atoms}}
Fred Drakef6669171998-05-06 19:52:49 +000046\index{atom}
47
Guido van Rossum3a0ad601998-07-23 21:57:42 +000048Atoms are the most basic elements of expressions. The simplest atoms
49are identifiers or literals. Forms enclosed in
Fred Drakef6669171998-05-06 19:52:49 +000050reverse quotes or in parentheses, brackets or braces are also
51categorized syntactically as atoms. The syntax for atoms is:
52
Fred Drakecb4638a2001-07-06 22:49:53 +000053\begin{productionlist}
54 \production{atom}
55 {\token{identifier} | \token{literal} | \token{enclosure}}
56 \production{enclosure}
57 {\token{parenth_form} | \token{list_display}
58 | \token{dict_display} | \token{string_conversion}}
59\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000060
Fred Drake2829f1c2001-06-23 05:27:20 +000061
Fred Drake020f8c01998-07-28 19:32:59 +000062\subsection{Identifiers (Names)\label{atom-identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +000063\index{name}
64\index{identifier}
65
66An identifier occurring as an atom is a reference to a local, global
67or built-in name binding. If a name is assigned to anywhere in a code
68block (even in unreachable code), and is not mentioned in a
Fred Drake5c07d9b1998-05-14 19:37:06 +000069\keyword{global} statement in that code block, then it refers to a local
Fred Drakef6669171998-05-06 19:52:49 +000070name throughout that code block. When it is not assigned to anywhere
71in the block, or when it is assigned to but also explicitly listed in
Fred Drake5c07d9b1998-05-14 19:37:06 +000072a \keyword{global} statement, it refers to a global name if one exists,
Fred Drakeac79e952001-03-06 07:32:11 +000073else to a built-in name (and this binding may dynamically
74change).\footnote{The Python interpreter provides a useful set of
75 predefined built-in functions. It is not recommended to reuse
76 (hide) these names with self defined objects. See the
77 \citetitle[../lib/built-in-funcs.html]{Python Library Reference} for
78 the descriptions of built-in functions and methods.}
Fred Drakef6669171998-05-06 19:52:49 +000079\indexii{name}{binding}
80\index{code block}
81\stindex{global}
82\indexii{built-in}{name}
83\indexii{global}{name}
84
85When the name is bound to an object, evaluation of the atom yields
86that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000087raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000088\exindex{NameError}
89
Guido van Rossum3a0ad601998-07-23 21:57:42 +000090\strong{Private name mangling:}%
91\indexii{name}{mangling}%
92\indexii{private}{names}%
93when an identifier that textually occurs in a class definition begins
94with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000095underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000096Private names are transformed to a longer form before code is
97generated for them. The transformation inserts the class name in
98front of the name, with leading underscores removed, and a single
99underscore inserted in front of the class name. For example, the
100identifier \code{__spam} occurring in a class named \code{Ham} will be
101transformed to \code{_Ham__spam}. This transformation is independent
102of the syntactical context in which the identifier is used. If the
103transformed name is extremely long (longer than 255 characters),
104implementation defined truncation may happen. If the class name
105consists only of underscores, no transformation is done.
106
Fred Drake2829f1c2001-06-23 05:27:20 +0000107
Fred Drake020f8c01998-07-28 19:32:59 +0000108\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000109\index{literal}
110
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000111Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +0000112
Fred Drakecb4638a2001-07-06 22:49:53 +0000113\begin{productionlist}
114 \production{literal}
115 {\token{stringliteral} | \token{integer}
116 | \token{longinteger} | \token{floatnumber}
117 | \token{imagnumber}}
118\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000119
120Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000121integer, long integer, floating point number, complex number) with the
122given value. The value may be approximated in the case of floating
123point and imaginary (complex) literals. See section \ref{literals}
124for details.
Fred Drakef6669171998-05-06 19:52:49 +0000125
126All literals correspond to immutable data types, and hence the
127object's identity is less important than its value. Multiple
128evaluations of literals with the same value (either the same
129occurrence in the program text or a different occurrence) may obtain
130the same object or a different object with the same value.
131\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000132\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000133
Fred Drake2829f1c2001-06-23 05:27:20 +0000134
Fred Drake020f8c01998-07-28 19:32:59 +0000135\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000136\index{parenthesized form}
137
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000138A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000139parentheses:
140
Fred Drakecb4638a2001-07-06 22:49:53 +0000141\begin{productionlist}
142 \production{parenth_form}
143 {"(" [\token{expression_list}] ")"}
144\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000145
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000146A parenthesized expression list yields whatever that expression list
147yields: if the list contains at least one comma, it yields a tuple;
148otherwise, it yields the single expression that makes up the
149expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000150
151An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000152tuples are immutable, the rules for literals apply (i.e., two
153occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000154\indexii{empty}{tuple}
155
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000156Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000157of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000158parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000159in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000160pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000161\index{comma}
162\indexii{tuple}{display}
163
Fred Drake2829f1c2001-06-23 05:27:20 +0000164
Fred Drake020f8c01998-07-28 19:32:59 +0000165\subsection{List displays\label{lists}}
Fred Drakef6669171998-05-06 19:52:49 +0000166\indexii{list}{display}
Skip Montanarob6559392000-09-11 16:31:55 +0000167\indexii{list}{comprehensions}
Fred Drakef6669171998-05-06 19:52:49 +0000168
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000169A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000170square brackets:
171
Fred Drakecb4638a2001-07-06 22:49:53 +0000172\begin{productionlist}
173 \production{list_display}
174 {"[" [\token{listmaker}] "]"}
175 \production{listmaker}
176 {\token{expression} ( \token{list_for}
177 | ( "," \token{expression})* [","] )}
178 \production{list_iter}
179 {\token{list_for} | \token{list_if}}
180 \production{list_for}
181 {"for" \token{expression_list} "in" \token{testlist}
182 [\token{list_iter}]}
183 \production{list_if}
184 {"if" \token{test} [\token{list_iter}]}
185\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000186
Skip Montanaro803d6e52000-08-12 18:09:51 +0000187A list display yields a new list object. Its contents are specified
188by providing either a list of expressions or a list comprehension.
Skip Montanarob6559392000-09-11 16:31:55 +0000189\indexii{list}{comprehensions}
Skip Montanaro803d6e52000-08-12 18:09:51 +0000190When a comma-separated list of expressions is supplied, its elements are
191evaluated from left to right and placed into the list object in that
192order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000193single expression followed by at least one \keyword{for} clause and zero or
194more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000195case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000196by considering each of the \keyword{for} or \keyword{if} clauses a block,
197nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000198left to right, and evaluating the expression to produce a list element
199each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000200\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000201\indexii{empty}{list}
202
Fred Drake2829f1c2001-06-23 05:27:20 +0000203
Fred Drake020f8c01998-07-28 19:32:59 +0000204\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000205\indexii{dictionary}{display}
206
207A dictionary display is a possibly empty series of key/datum pairs
208enclosed in curly braces:
209\index{key}
210\index{datum}
211\index{key/datum pair}
212
Fred Drakecb4638a2001-07-06 22:49:53 +0000213\begin{productionlist}
214 \production{dict_display}
215 {"{" [\token{key_datum_list}] "}"}
216 \production{key_datum_list}
217 {\token{key_datum} ("," \token{key_datum})* [","]}
218 \production{key_datum}
219 {\token{expression} ":" \token{expression}}
220\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000221
222A dictionary display yields a new dictionary object.
223\obindex{dictionary}
224
225The key/datum pairs are evaluated from left to right to define the
226entries of the dictionary: each key object is used as a key into the
227dictionary to store the corresponding datum.
228
229Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000230section \ref{types}. (To summarize,the key type should be hashable,
231which excludes all mutable objects.) Clashes between duplicate keys
232are not detected; the last datum (textually rightmost in the display)
233stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000234\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000235
Fred Drake2829f1c2001-06-23 05:27:20 +0000236
Fred Drake020f8c01998-07-28 19:32:59 +0000237\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000238\indexii{string}{conversion}
239\indexii{reverse}{quotes}
240\indexii{backward}{quotes}
241\index{back-quotes}
242
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000243A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000244backward) quotes:
245
Fred Drakecb4638a2001-07-06 22:49:53 +0000246\begin{productionlist}
247 \production{string_conversion}
248 {"`" \token{expression_list} "`"}
249\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000250
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000251A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000252converts the resulting object into a string according to rules
253specific to its type.
254
Fred Drake5c07d9b1998-05-14 19:37:06 +0000255If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000256dictionary containing only objects whose type is one of these, the
257resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000258the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000259same value (or an approximation, if floating point numbers are
260involved).
261
262(In particular, converting a string adds quotes around it and converts
263``funny'' characters to escape sequences that are safe to print.)
264
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000265It is illegal to attempt to convert recursive objects (e.g., lists or
Fred Drakef6669171998-05-06 19:52:49 +0000266dictionaries that contain a reference to themselves, directly or
267indirectly.)
268\obindex{recursive}
269
Fred Drake5c07d9b1998-05-14 19:37:06 +0000270The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000271conversion in its argument as enclosing it in parentheses and reverse
272quotes does. The built-in function \function{str()} performs a
273similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000274\bifuncindex{repr}
275\bifuncindex{str}
276
Fred Drake2829f1c2001-06-23 05:27:20 +0000277
Fred Drake020f8c01998-07-28 19:32:59 +0000278\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000279\index{primary}
280
281Primaries represent the most tightly bound operations of the language.
282Their syntax is:
283
Fred Drakecb4638a2001-07-06 22:49:53 +0000284\begin{productionlist}
285 \production{primary}
286 {\token{atom} | \token{attributeref}
287 | \token{subscription} | \token{slicing} | \token{call}}
288\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000289
Fred Drake2829f1c2001-06-23 05:27:20 +0000290
Fred Drake020f8c01998-07-28 19:32:59 +0000291\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000292\indexii{attribute}{reference}
293
294An attribute reference is a primary followed by a period and a name:
295
Fred Drakecb4638a2001-07-06 22:49:53 +0000296\begin{productionlist}
297 \production{attributeref}
298 {\token{primary} "." \token{identifier}}
299\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000300
301The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000302attribute references, e.g., a module, list, or an instance. This
303object is then asked to produce the attribute whose name is the
304identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000305\exception{AttributeError}\exindex{AttributeError} is raised.
306Otherwise, the type and value of the object produced is determined by
307the object. Multiple evaluations of the same attribute reference may
308yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000309\obindex{module}
310\obindex{list}
311
Fred Drake2829f1c2001-06-23 05:27:20 +0000312
Fred Drake020f8c01998-07-28 19:32:59 +0000313\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000314\index{subscription}
315
316A subscription selects an item of a sequence (string, tuple or list)
317or mapping (dictionary) object:
318\obindex{sequence}
319\obindex{mapping}
320\obindex{string}
321\obindex{tuple}
322\obindex{list}
323\obindex{dictionary}
324\indexii{sequence}{item}
325
Fred Drakecb4638a2001-07-06 22:49:53 +0000326\begin{productionlist}
327 \production{subscription}
328 {\token{primary} "[" \token{expression_list} "]"}
329\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000330
331The primary must evaluate to an object of a sequence or mapping type.
332
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000333If the primary is a mapping, the expression list must evaluate to an
334object whose value is one of the keys of the mapping, and the
335subscription selects the value in the mapping that corresponds to that
336key. (The expression list is a tuple except if it has exactly one
337item.)
Fred Drakef6669171998-05-06 19:52:49 +0000338
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000339If the primary is a sequence, the expression (list) must evaluate to a
340plain integer. If this value is negative, the length of the sequence
341is added to it (so that, e.g., \code{x[-1]} selects the last item of
342\code{x}.) The resulting value must be a nonnegative integer less
343than the number of items in the sequence, and the subscription selects
344the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000345
346A string's items are characters. A character is not a separate data
347type but a string of exactly one character.
348\index{character}
349\indexii{string}{item}
350
Fred Drake2829f1c2001-06-23 05:27:20 +0000351
Fred Drake020f8c01998-07-28 19:32:59 +0000352\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000353\index{slicing}
354\index{slice}
355
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000356A slicing selects a range of items in a sequence object (e.g., a
357string, tuple or list). Slicings may be used as expressions or as
358targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000359\obindex{sequence}
360\obindex{string}
361\obindex{tuple}
362\obindex{list}
363
Fred Drakecb4638a2001-07-06 22:49:53 +0000364\begin{productionlist}
365 \production{slicing}
366 {\token{simple_slicing} | \token{extended_slicing}}
367 \production{simple_slicing}
368 {\token{primary} "[" \token{short_slice} "]"}
369 \production{extended_slicing}
370 {\token{primary} "[" \token{slice_list} "]" }
371 \production{slice_list}
372 {\token{slice_item} ("," \token{slice_item})* [","]}
373 \production{slice_item}
374 {\token{expression} | \token{proper_slice} | \token{ellipsis}}
375 \production{proper_slice}
376 {\token{short_slice} | \token{long_slice}}
377 \production{short_slice}
378 {[\token{lower_bound}] ":" [\token{upper_bound}]}
379 \production{long_slice}
380 {\token{short_slice} ":" [\token{stride}]}
381 \production{lower_bound}
382 {\token{expression}}
383 \production{upper_bound}
384 {\token{expression}}
385 \production{stride}
386 {\token{expression}}
387 \production{ellipsis}
388 {"..."}
389\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000390
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000391There is ambiguity in the formal syntax here: anything that looks like
392an expression list also looks like a slice list, so any subscription
393can be interpreted as a slicing. Rather than further complicating the
394syntax, this is disambiguated by defining that in this case the
395interpretation as a subscription takes priority over the
396interpretation as a slicing (this is the case if the slice list
397contains no proper slice nor ellipses). Similarly, when the slice
398list has exactly one short slice and no trailing comma, the
399interpretation as a simple slicing takes priority over that as an
400extended slicing.\indexii{extended}{slicing}
401
402The semantics for a simple slicing are as follows. The primary must
403evaluate to a sequence object. The lower and upper bound expressions,
404if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000405\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000406sequence's length is added to it. The slicing now selects all items
407with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000408\code{\var{i} <= \var{k} < \var{j}} where \var{i}
409and \var{j} are the specified lower and upper bounds. This may be an
410empty sequence. It is not an error if \var{i} or \var{j} lie outside the
411range of valid indexes (such items don't exist so they aren't
412selected).
413
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000414The semantics for an extended slicing are as follows. The primary
415must evaluate to a mapping object, and it is indexed with a key that
416is constructed from the slice list, as follows. If the slice list
417contains at least one comma, the key is a tuple containing the
418conversion of the slice items; otherwise, the conversion of the lone
419slice item is the key. The conversion of a slice item that is an
420expression is that expression. The conversion of an ellipsis slice
421item is the built-in \code{Ellipsis} object. The conversion of a
422proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000423\member{start}, \member{stop} and \member{step} attributes are the
424values of the expressions given as lower bound, upper bound and
425stride, respectively, substituting \code{None} for missing
426expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000427\withsubitem{(slice object attribute)}{\ttindex{start}
428 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000429
Fred Drake2829f1c2001-06-23 05:27:20 +0000430
Fred Drake020f8c01998-07-28 19:32:59 +0000431\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000432\index{call}
433
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000434A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000435series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000436\obindex{callable}
437
Fred Drakecb4638a2001-07-06 22:49:53 +0000438\begin{productionlist}
439 \production{call}
440 {\token{primary} "(" [\token{argument_list} [","]] ")"}
441 \production{argument_list}
442 {\token{positional_arguments} ["," \token{keyword_arguments}]
443 | \token{keyword_arguments}}
444 \production{positional_arguments}
445 {\token{expression} ("," \token{expression})*}
446 \production{keyword_arguments}
447 {\token{keyword_item} ("," \token{keyword_item})*}
448 \production{keyword_item}
449 {\token{identifier} "=" \token{expression}}
450\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000451
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000452A trailing comma may be present after an argument list but does not
453affect the semantics.
454
Fred Drakef6669171998-05-06 19:52:49 +0000455The primary must evaluate to a callable object (user-defined
456functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000457objects, methods of class instances, and certain class instances
458themselves are callable; extensions may define additional callable
459object types). All argument expressions are evaluated before the call
460is attempted. Please refer to section \ref{function} for the syntax
461of formal parameter lists.
462
463If keyword arguments are present, they are first converted to
464positional arguments, as follows. First, a list of unfilled slots is
465created for the formal parameters. If there are N positional
466arguments, they are placed in the first N slots. Next, for each
467keyword argument, the identifier is used to determine the
468corresponding slot (if the identifier is the same as the first formal
469parameter name, the first slot is used, and so on). If the slot is
470already filled, a \exception{TypeError} exception is raised.
471Otherwise, the value of the argument is placed in the slot, filling it
472(even if the expression is \code{None}, it fills the slot). When all
473arguments have been processed, the slots that are still unfilled are
474filled with the corresponding default value from the function
475definition. (Default values are calculated, once, when the function
476is defined; thus, a mutable object such as a list or dictionary used
477as default value will be shared by all calls that don't specify an
478argument value for the corresponding slot; this should usually be
479avoided.) If there are any unfilled slots for which no default value
480is specified, a \exception{TypeError} exception is raised. Otherwise,
481the list of filled slots is used as the argument list for the call.
482
483If there are more positional arguments than there are formal parameter
484slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000485parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000486case, that formal parameter receives a tuple containing the excess
487positional arguments (or an empty tuple if there were no excess
488positional arguments).
489
490If any keyword argument does not correspond to a formal parameter
491name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000492parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000493case, that formal parameter receives a dictionary containing the
494excess keyword arguments (using the keywords as keys and the argument
495values as corresponding values), or a (new) empty dictionary if there
496were no excess keyword arguments.
497
Fred Drakeea81edf1998-11-25 17:51:15 +0000498Formal parameters using the syntax \samp{*identifier} or
499\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000500as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000501\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000502outermost sublist corresponds to a single unnamed argument slot, and
503the argument value is assigned to the sublist using the usual tuple
504assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000505
Fred Drake5c07d9b1998-05-14 19:37:06 +0000506A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000507raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000508of the callable object.
509
510If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000511
512\begin{description}
513
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000514\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000515executed, passing it the argument list. The first thing the code
516block will do is bind the formal parameters to the arguments; this is
517described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000518\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000519function call.
520\indexii{function}{call}
521\indexiii{user-defined}{function}{call}
522\obindex{user-defined function}
523\obindex{function}
524
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000525\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000526interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
527Library Reference} for the descriptions of built-in functions and
528methods.
Fred Drakef6669171998-05-06 19:52:49 +0000529\indexii{function}{call}
530\indexii{built-in function}{call}
531\indexii{method}{call}
532\indexii{built-in method}{call}
533\obindex{built-in method}
534\obindex{built-in function}
535\obindex{method}
536\obindex{function}
537
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000538\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000539\obindex{class}
540\indexii{class object}{call}
541
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000542\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000543function is called, with an argument list that is one longer than the
544argument list of the call: the instance becomes the first argument.
545\obindex{class instance}
546\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000547\indexii{class instance}{call}
548
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000549\item[a class instance:] The class must define a \method{__call__()}
550method; the effect is then the same as if that method was called.
551\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000552\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000553
Fred Drakef6669171998-05-06 19:52:49 +0000554\end{description}
555
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000556
Fred Drake020f8c01998-07-28 19:32:59 +0000557\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000558
559The power operator binds more tightly than unary operators on its
560left; it binds less tightly than unary operators on its right. The
561syntax is:
562
Fred Drakecb4638a2001-07-06 22:49:53 +0000563\begin{productionlist}
564 \production{power}
565 {\token{primary} ["**" \token{u_expr}]}
566\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000567
568Thus, in an unparenthesized sequence of power and unary operators, the
569operators are evaluated from right to left (this does not constrain
570the evaluation order for the operands).
571
572The power operator has the same semantics as the built-in
573\function{pow()} function, when called with two arguments: it yields
574its left argument raised to the power of its right argument. The
575numeric arguments are first converted to a common type. The result
576type is that of the arguments after coercion; if the result is not
577expressible in that type (as in raising an integer to a negative
578power, or a negative floating point number to a broken power), a
579\exception{TypeError} exception is raised.
580
581
Fred Drakee15956b2000-04-03 04:51:13 +0000582\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000583\indexiii{unary}{arithmetic}{operation}
584\indexiii{unary}{bit-wise}{operation}
585
586All unary arithmetic (and bit-wise) operations have the same priority:
587
Fred Drakecb4638a2001-07-06 22:49:53 +0000588\begin{productionlist}
589 \production{u_expr}
590 {\token{power} | "-" \token{u_expr}
591 | "+" \token{u_expr} | "~" \token{u_expr}}
592\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000593
Fred Drake5c07d9b1998-05-14 19:37:06 +0000594The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000595numeric argument.
596\index{negation}
597\index{minus}
598
Fred Drake5c07d9b1998-05-14 19:37:06 +0000599The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000600unchanged.
601\index{plus}
602
Fred Drakee15956b2000-04-03 04:51:13 +0000603The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000604of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000605\code{x} is defined as \code{-(x+1)}. It only applies to integral
606numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000607\index{inversion}
608
609In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000610a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000611\exindex{TypeError}
612
Fred Drake2829f1c2001-06-23 05:27:20 +0000613
Fred Drake020f8c01998-07-28 19:32:59 +0000614\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000615\indexiii{binary}{arithmetic}{operation}
616
617The binary arithmetic operations have the conventional priority
618levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000619non-numeric types. Apart from the power operator, there are only two
620levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000621operators:
622
Fred Drakecb4638a2001-07-06 22:49:53 +0000623\begin{productionlist}
624 \production{m_expr}
625 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
626 | \token{m_expr} "/" \token{u_expr}
627 | \token{m_expr} "\%" \token{u_expr}}
628 \production{a_expr}
629 {\token{m_expr} | \token{aexpr} "+" \token{m_expr}
630 \token{aexpr} "-" \token{m_expr}}
631\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000632
Fred Drake5c07d9b1998-05-14 19:37:06 +0000633The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000634arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000635must be an integer (plain or long) and the other must be a sequence.
636In the former case, the numbers are converted to a common type and
637then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000638performed; a negative repetition factor yields an empty sequence.
639\index{multiplication}
640
Fred Drake5c07d9b1998-05-14 19:37:06 +0000641The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000642arguments. The numeric arguments are first converted to a common
643type. Plain or long integer division yields an integer of the same
644type; the result is that of mathematical division with the `floor'
645function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000646\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000647\exindex{ZeroDivisionError}
648\index{division}
649
Fred Drake5c07d9b1998-05-14 19:37:06 +0000650The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000651division of the first argument by the second. The numeric arguments
652are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000653the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000654point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000655\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
656yields a result with the same sign as its second operand (or zero);
657the absolute value of the result is strictly smaller than the second
658operand.
Fred Drakef6669171998-05-06 19:52:49 +0000659\index{modulo}
660
661The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000662following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
663modulo are also connected with the built-in function \function{divmod()}:
664\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000665floating point and complex numbers; there similar identities hold
666approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
667\code{floor(x/y) - 1} (for floats),\footnote{
668 If x is very close to an exact integer multiple of y, it's
669 possible for \code{floor(x/y)} to be one larger than
670 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
671 the latter result, in order to preserve that \code{divmod(x,y)[0]
672 * y + x \%{} y} be very close to \code{x}.
673} or \code{floor((x/y).real)} (for
674complex).
Fred Drakef6669171998-05-06 19:52:49 +0000675
Fred Drake5c07d9b1998-05-14 19:37:06 +0000676The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000677The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000678same type. In the former case, the numbers are converted to a common
679type and then added together. In the latter case, the sequences are
680concatenated.
681\index{addition}
682
Fred Drake5c07d9b1998-05-14 19:37:06 +0000683The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000684arguments. The numeric arguments are first converted to a common
685type.
686\index{subtraction}
687
Fred Drake2829f1c2001-06-23 05:27:20 +0000688
Fred Drake020f8c01998-07-28 19:32:59 +0000689\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000690\indexii{shifting}{operation}
691
692The shifting operations have lower priority than the arithmetic
693operations:
694
Fred Drakecb4638a2001-07-06 22:49:53 +0000695\begin{productionlist}
696 \production{shift_expr}
697 {\token{a_expr}
698 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
699\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000700
701These operators accept plain or long integers as arguments. The
702arguments are converted to a common type. They shift the first
703argument to the left or right by the number of bits given by the
704second argument.
705
706A right shift by \var{n} bits is defined as division by
707\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
708multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000709no overflow check so in that case the operation drops bits and flips
710the sign if the result is not less than \code{pow(2,31)} in absolute
711value. Negative shift counts raise a \exception{ValueError}
712exception.
Fred Drakef6669171998-05-06 19:52:49 +0000713\exindex{ValueError}
714
Fred Drake2829f1c2001-06-23 05:27:20 +0000715
Fred Drake020f8c01998-07-28 19:32:59 +0000716\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000717\indexiii{binary}{bit-wise}{operation}
718
719Each of the three bitwise operations has a different priority level:
720
Fred Drakecb4638a2001-07-06 22:49:53 +0000721\begin{productionlist}
722 \production{and_expr}
723 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
724 \production{xor_expr}
725 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
726 \production{or_expr}
727 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
728\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000729
Fred Drake5c07d9b1998-05-14 19:37:06 +0000730The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000731must be plain or long integers. The arguments are converted to a
732common type.
733\indexii{bit-wise}{and}
734
Fred Drake5c07d9b1998-05-14 19:37:06 +0000735The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000736arguments, which must be plain or long integers. The arguments are
737converted to a common type.
738\indexii{bit-wise}{xor}
739\indexii{exclusive}{or}
740
Fred Drake5c07d9b1998-05-14 19:37:06 +0000741The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000742arguments, which must be plain or long integers. The arguments are
743converted to a common type.
744\indexii{bit-wise}{or}
745\indexii{inclusive}{or}
746
Fred Drake2829f1c2001-06-23 05:27:20 +0000747
Fred Drake020f8c01998-07-28 19:32:59 +0000748\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000749\index{comparison}
750
Fred Drake1156f622000-09-19 18:10:05 +0000751Unlike C, all comparison operations in Python have the same priority,
752which is lower than that of any arithmetic, shifting or bitwise
753operation. Also unlike C, expressions like \code{a < b < c} have the
754interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000755\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000756
Fred Drakecb4638a2001-07-06 22:49:53 +0000757\begin{productionlist}
758 \production{comparison}
759 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
760 \production{comp_operator}
761 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
762 | "is" ["not"] | ["not"] "in"}
763\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000764
Fred Drake5c07d9b1998-05-14 19:37:06 +0000765Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000766
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000767Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000768equivalent to \code{x < y and y <= z}, except that \code{y} is
769evaluated only once (but in both cases \code{z} is not evaluated at all
770when \code{x < y} is found to be false).
771\indexii{chaining}{comparisons}
772
773Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
774expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
775operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000776to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000777\var{y opy z}, except that each expression is evaluated at most once.
778
779Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000780between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000781perfectly legal (though perhaps not pretty).
782
Fred Drake5c07d9b1998-05-14 19:37:06 +0000783The forms \code{<>} and \code{!=} are equivalent; for consistency with
784C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000785\code{<>} is also accepted. The \code{<>} spelling is considered
786obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000787
Fred Drake1156f622000-09-19 18:10:05 +0000788The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
789\code{!=} compare
790the values of two objects. The objects need not have the same type.
Fred Drakef6669171998-05-06 19:52:49 +0000791If both are numbers, they are coverted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000792objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000793ordered consistently but arbitrarily.
794
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000795(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000796definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000797\keyword{not in} operators. In the future, the comparison rules for
798objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000799
800Comparison of objects of the same type depends on the type:
801
802\begin{itemize}
803
804\item
805Numbers are compared arithmetically.
806
807\item
808Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000809(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000810characters. Unicode and 8-bit strings are fully interoperable in this
811behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000812
813\item
814Tuples and lists are compared lexicographically using comparison of
815corresponding items.
816
817\item
818Mappings (dictionaries) are compared through lexicographic
Fred Drakeb55ce1e1999-04-05 21:32:52 +0000819comparison of their sorted (key, value) lists.\footnote{
820This is expensive since it requires sorting the keys first,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000821but it is about the only sensible definition. An earlier version of
822Python compared dictionaries by identity only, but this caused
823surprises because people expected to be able to test a dictionary for
824emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000825
826\item
827Most other types compare unequal unless they are the same object;
828the choice whether one object is considered smaller or larger than
829another one is made arbitrarily but consistently within one
830execution of a program.
831
832\end{itemize}
833
Fred Drake7399b9e2000-07-11 19:43:47 +0000834The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000835membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
836is a member of the set \var{s}, and false otherwise. \code{\var{x}
837not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
838The set membership test has traditionally been bound to sequences; an
839object is a member of a set if the set is a sequence and contains an
840element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000841to support membership tests without being a sequence. In particular,
842dictionaries support memership testing as a nicer way of spelling
843\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000844
Fred Drake34bafcc2001-01-14 02:57:14 +0000845For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000846only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000847\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000848
Fred Drake1156f622000-09-19 18:10:05 +0000849For the Unicode and string types, \code{\var{x} in \var{y}} is true if
850and only if there exists an index \var{i} such that \code{\var{x} ==
851\var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
852Unicode object of length \code{1}, a \exception{TypeError} exception
853is raised.
Fred Drake7399b9e2000-07-11 19:43:47 +0000854
855For user-defined classes which define the \method{__contains__()} method,
856\code{\var{x} in \var{y}} is true if and only if
857\code{\var{y}.__contains__(\var{x})} is true.
858
859For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000860do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
861and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000862\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
863do not raise \exception{IndexError} exception. (If any other exception
864is raised, it is as if \keyword{in} raised that exception).
865
866The operator \keyword{not in} is defined to have the inverse true value
867of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000868\opindex{in}
869\opindex{not in}
870\indexii{membership}{test}
871\obindex{sequence}
872
Fred Drake5c07d9b1998-05-14 19:37:06 +0000873The operators \keyword{is} and \keyword{is not} test for object identity:
874\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
875are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000876truth value.
877\opindex{is}
878\opindex{is not}
879\indexii{identity}{test}
880
Fred Drake2829f1c2001-06-23 05:27:20 +0000881
Fred Drake020f8c01998-07-28 19:32:59 +0000882\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000883\indexii{Boolean}{operation}
884
885Boolean operations have the lowest priority of all Python operations:
886
Fred Drakecb4638a2001-07-06 22:49:53 +0000887\begin{productionlist}
888 \production{expression}
889 {\token{or_test} | \token{lambda_form}}
890 \production{or_test}
891 {\token{and_test} | \token{or_test} "or" \token{and_test}}
892 \production{and_test}
893 {\token{not_test} | \token{and_test} "and" \token{not_test}}
894 \production{not_test}
895 {\token{comparison} | "not" \token{not_test}}
896 \production{lambda_form}
897 {"lambda" [\token{parameter_list}]: \token{expression}}
898\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000899
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000900In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000901used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000902as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000903(strings, tuples and lists), and empty mappings (dictionaries). All
904other values are interpreted as true.
905
Fred Drake5c07d9b1998-05-14 19:37:06 +0000906The operator \keyword{not} yields \code{1} if its argument is false,
907\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000908\opindex{not}
909
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000910The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000911\var{x} is false, its value is returned; otherwise, \var{y} is
912evaluated and the resulting value is returned.
913\opindex{and}
914
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000915The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000916\var{x} is true, its value is returned; otherwise, \var{y} is
917evaluated and the resulting value is returned.
918\opindex{or}
919
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000920(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000921and type they return to \code{0} and \code{1}, but rather return the
922last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000923This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000924replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000925\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000926invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000927same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000928not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000929
930Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000931expressions. They are a shorthand to create anonymous functions; the
932expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000933yields a function object that behaves virtually identical to one
934defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000935
936\begin{verbatim}
937def name(arguments):
938 return expression
939\end{verbatim}
940
941See section \ref{function} for the syntax of parameter lists. Note
942that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000943\label{lambda}
944\indexii{lambda}{expression}
945\indexii{lambda}{form}
946\indexii{anonmymous}{function}
947
Fred Drake88382692001-06-05 02:17:02 +0000948\strong{Programmer's note:} Prior to Python 2.1, a lambda form defined
949inside a function has no access to names defined in the function's
950namespace. This is because Python had only two scopes: local and
951global. A common work-around was to use default argument values to
952pass selected variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000953
954\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000955def make_incrementor(increment):
956 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +0000957\end{verbatim}
958
Fred Drake88382692001-06-05 02:17:02 +0000959As of Python 2.1, nested scopes were introduced, and this work-around
960has not been necessary. Python 2.1 supports nested scopes in modules
961which include the statement \samp{from __future__ import
962nested_scopes}, and more recent versions of Python enable nested
963scopes by default. This version works starting with Python 2.1:
964
965\begin{verbatim}
966from __future__ import nested_scopes
967
968def make_incrementor(increment):
969 return lambda x: x+increment
970\end{verbatim}
971
972
Fred Drake020f8c01998-07-28 19:32:59 +0000973\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000974\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +0000975
Fred Drakecb4638a2001-07-06 22:49:53 +0000976\begin{productionlist}
977 \production{expression_list}
978 {\token{expression} ( "," \token{expression} )* [","]}
979\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000980
Fred Drakec009d192000-04-25 21:09:10 +0000981An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000982tuple. The length of the tuple is the number of expressions in the
983list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +0000984\obindex{tuple}
985
986The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000987\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +0000988expression without a trailing comma doesn't create a
989tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +0000990(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000991\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000992\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +0000993
Fred Draked09120b1999-04-29 16:43:42 +0000994
Fred Drake020f8c01998-07-28 19:32:59 +0000995\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +0000996
Fred Draked09120b1999-04-29 16:43:42 +0000997The following table summarizes the operator
998precedences\indexii{operator}{precedence} in Python, from lowest
999precedence (least binding) to highest precedence (most binding).
1000Operators in the same box have the same precedence. Unless the syntax
1001is explicitly given, operators are binary. Operators in the same box
1002group left to right (except for comparisons, which chain from left to
Fred Drake2a222002000-12-11 22:39:24 +00001003right --- see above, and exponentiation, which groups from right to
1004left).
Fred Drakef6669171998-05-06 19:52:49 +00001005
Fred Draked09120b1999-04-29 16:43:42 +00001006\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001007 \lineii{\keyword{lambda}} {Lambda expression}
1008 \hline
1009 \lineii{\keyword{or}} {Boolean OR}
1010 \hline
1011 \lineii{\keyword{and}} {Boolean AND}
1012 \hline
1013 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1014 \hline
1015 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1016 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1017 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +00001018 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001019 {Comparisons}
1020 \hline
1021 \lineii{\code{|}} {Bitwise OR}
1022 \hline
1023 \lineii{\code{\^}} {Bitwise XOR}
1024 \hline
1025 \lineii{\code{\&}} {Bitwise AND}
1026 \hline
Fred Drake24e7a292001-04-12 12:37:03 +00001027 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001028 \hline
1029 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1030 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001031 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001032 {Multiplication, division, remainder}
1033 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001034 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1035 \lineii{\code{\~\var{x}}} {Bitwise not}
1036 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001037 \lineii{\code{**}} {Exponentiation}
1038 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001039 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1040 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1041 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1042 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001043 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001044 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1045 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1046 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1047 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1048\end{tableii}