blob: 9ed93370b64c6903d38280216849cc43068cdc1b [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
Tim Peters20524db2001-10-01 20:22:45 +0000194more \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,
Tim Peters20524db2001-10-01 20:22:45 +0000197nesting 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}
Michael W. Hudson850d3982001-12-12 11:56:33 +0000442 {\token{positional_arguments} ["," \token{keyword_arguments}
443 ["," "*" \token{expression} ["," "**" \token{expression}]]]
444 | \token{keyword_arguments} ["," "*" \token{expression}
445 ["," "**" \token{expression}]]
446 | "*" \token{expression} ["," "**" \token{expression}]
447 | "**" \token{expression}
448 }
Fred Drakecb4638a2001-07-06 22:49:53 +0000449 \production{positional_arguments}
450 {\token{expression} ("," \token{expression})*}
451 \production{keyword_arguments}
452 {\token{keyword_item} ("," \token{keyword_item})*}
453 \production{keyword_item}
454 {\token{identifier} "=" \token{expression}}
455\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000456
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000457A trailing comma may be present after an argument list but does not
458affect the semantics.
459
Fred Drakef6669171998-05-06 19:52:49 +0000460The primary must evaluate to a callable object (user-defined
461functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000462objects, methods of class instances, and certain class instances
463themselves are callable; extensions may define additional callable
464object types). All argument expressions are evaluated before the call
465is attempted. Please refer to section \ref{function} for the syntax
466of formal parameter lists.
467
468If keyword arguments are present, they are first converted to
469positional arguments, as follows. First, a list of unfilled slots is
470created for the formal parameters. If there are N positional
471arguments, they are placed in the first N slots. Next, for each
472keyword argument, the identifier is used to determine the
473corresponding slot (if the identifier is the same as the first formal
474parameter name, the first slot is used, and so on). If the slot is
475already filled, a \exception{TypeError} exception is raised.
476Otherwise, the value of the argument is placed in the slot, filling it
477(even if the expression is \code{None}, it fills the slot). When all
478arguments have been processed, the slots that are still unfilled are
479filled with the corresponding default value from the function
480definition. (Default values are calculated, once, when the function
481is defined; thus, a mutable object such as a list or dictionary used
482as default value will be shared by all calls that don't specify an
483argument value for the corresponding slot; this should usually be
484avoided.) If there are any unfilled slots for which no default value
485is specified, a \exception{TypeError} exception is raised. Otherwise,
486the list of filled slots is used as the argument list for the call.
487
488If there are more positional arguments than there are formal parameter
489slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000490parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000491case, that formal parameter receives a tuple containing the excess
492positional arguments (or an empty tuple if there were no excess
493positional arguments).
494
495If any keyword argument does not correspond to a formal parameter
496name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000497parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000498case, that formal parameter receives a dictionary containing the
499excess keyword arguments (using the keywords as keys and the argument
500values as corresponding values), or a (new) empty dictionary if there
501were no excess keyword arguments.
502
Michael W. Hudson850d3982001-12-12 11:56:33 +0000503If the syntax \samp{*expression} appears in the function call,
504\samp{expression} must evaluate to a sequence. Elements from this
505sequence are treated as if they were additional positional arguments;
506if there are postional arguments \var{x1},...,\var{xN} , and
507\samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
508is equivalent to a call with M+N positional arguments
509\var{x1},...,\var{xN},\var{y1},...,\var{yM}.
510
511A consequence of this is that although the \samp{*expression} syntax
512appears \emph{after} any keyword arguments, it is processed
Fred Drakeb062cb22001-12-14 16:57:31 +0000513\emph{before} the keyword arguments (and the
514\samp{**expression} argument, if any -- see below). So:
Michael W. Hudson850d3982001-12-12 11:56:33 +0000515
516\begin{verbatim}
517>>> def f(a, b):
518... print a, b
519...
520>>> f(b=1, *(2,))
5212 1
522>>> f(a=1, *(2,))
523Traceback (most recent call last):
524 File "<stdin>", line 1, in ?
525TypeError: f() got multiple values for keyword argument 'a'
526>>> f(1, *(2,))
5271 2
528\end{verbatim}
529
Fred Drakeb062cb22001-12-14 16:57:31 +0000530It is unusual for both keyword arguments and the
531\samp{*expression} syntax to be used in the same call, so in practice
532this confusion does not arise.
Michael W. Hudson850d3982001-12-12 11:56:33 +0000533
534If the syntax \samp{**expression} appears in the function call,
535\samp{expression} must evaluate to a (subclass of) dictionary, the
536contents of which are treated as additional keyword arguments. In the
537case of a keyword appearing in both \samp{expression} and as an
538explicit keyword argument, a \exception{TypeError} exception is
539raised.
540
Fred Drakeea81edf1998-11-25 17:51:15 +0000541Formal parameters using the syntax \samp{*identifier} or
542\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000543as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000544\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000545outermost sublist corresponds to a single unnamed argument slot, and
546the argument value is assigned to the sublist using the usual tuple
547assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000548
Fred Drake5c07d9b1998-05-14 19:37:06 +0000549A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000550raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000551of the callable object.
552
553If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000554
555\begin{description}
556
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000557\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000558executed, passing it the argument list. The first thing the code
559block will do is bind the formal parameters to the arguments; this is
560described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000561\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000562function call.
563\indexii{function}{call}
564\indexiii{user-defined}{function}{call}
565\obindex{user-defined function}
566\obindex{function}
567
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000568\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000569interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
570Library Reference} for the descriptions of built-in functions and
571methods.
Fred Drakef6669171998-05-06 19:52:49 +0000572\indexii{function}{call}
573\indexii{built-in function}{call}
574\indexii{method}{call}
575\indexii{built-in method}{call}
576\obindex{built-in method}
577\obindex{built-in function}
578\obindex{method}
579\obindex{function}
580
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000581\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000582\obindex{class}
583\indexii{class object}{call}
584
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000585\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000586function is called, with an argument list that is one longer than the
587argument list of the call: the instance becomes the first argument.
588\obindex{class instance}
589\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000590\indexii{class instance}{call}
591
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000592\item[a class instance:] The class must define a \method{__call__()}
593method; the effect is then the same as if that method was called.
594\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000595\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000596
Fred Drakef6669171998-05-06 19:52:49 +0000597\end{description}
598
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000599
Fred Drake020f8c01998-07-28 19:32:59 +0000600\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000601
602The power operator binds more tightly than unary operators on its
603left; it binds less tightly than unary operators on its right. The
604syntax is:
605
Fred Drakecb4638a2001-07-06 22:49:53 +0000606\begin{productionlist}
607 \production{power}
608 {\token{primary} ["**" \token{u_expr}]}
609\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000610
611Thus, in an unparenthesized sequence of power and unary operators, the
612operators are evaluated from right to left (this does not constrain
613the evaluation order for the operands).
614
615The power operator has the same semantics as the built-in
616\function{pow()} function, when called with two arguments: it yields
617its left argument raised to the power of its right argument. The
618numeric arguments are first converted to a common type. The result
619type is that of the arguments after coercion; if the result is not
620expressible in that type (as in raising an integer to a negative
621power, or a negative floating point number to a broken power), a
622\exception{TypeError} exception is raised.
623
624
Fred Drakee15956b2000-04-03 04:51:13 +0000625\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000626\indexiii{unary}{arithmetic}{operation}
627\indexiii{unary}{bit-wise}{operation}
628
629All unary arithmetic (and bit-wise) operations have the same priority:
630
Fred Drakecb4638a2001-07-06 22:49:53 +0000631\begin{productionlist}
632 \production{u_expr}
633 {\token{power} | "-" \token{u_expr}
634 | "+" \token{u_expr} | "~" \token{u_expr}}
635\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000636
Fred Drake5c07d9b1998-05-14 19:37:06 +0000637The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000638numeric argument.
639\index{negation}
640\index{minus}
641
Fred Drake5c07d9b1998-05-14 19:37:06 +0000642The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000643unchanged.
644\index{plus}
645
Fred Drakee15956b2000-04-03 04:51:13 +0000646The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000647of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000648\code{x} is defined as \code{-(x+1)}. It only applies to integral
649numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000650\index{inversion}
651
652In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000653a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000654\exindex{TypeError}
655
Fred Drake2829f1c2001-06-23 05:27:20 +0000656
Fred Drake020f8c01998-07-28 19:32:59 +0000657\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000658\indexiii{binary}{arithmetic}{operation}
659
660The binary arithmetic operations have the conventional priority
661levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000662non-numeric types. Apart from the power operator, there are only two
663levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000664operators:
665
Fred Drakecb4638a2001-07-06 22:49:53 +0000666\begin{productionlist}
667 \production{m_expr}
668 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
669 | \token{m_expr} "/" \token{u_expr}
670 | \token{m_expr} "\%" \token{u_expr}}
671 \production{a_expr}
672 {\token{m_expr} | \token{aexpr} "+" \token{m_expr}
673 \token{aexpr} "-" \token{m_expr}}
674\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000675
Fred Drake5c07d9b1998-05-14 19:37:06 +0000676The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000677arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000678must be an integer (plain or long) and the other must be a sequence.
679In the former case, the numbers are converted to a common type and
680then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000681performed; a negative repetition factor yields an empty sequence.
682\index{multiplication}
683
Fred Drake5c07d9b1998-05-14 19:37:06 +0000684The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000685arguments. The numeric arguments are first converted to a common
686type. Plain or long integer division yields an integer of the same
687type; the result is that of mathematical division with the `floor'
688function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000689\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000690\exindex{ZeroDivisionError}
691\index{division}
692
Fred Drake5c07d9b1998-05-14 19:37:06 +0000693The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000694division of the first argument by the second. The numeric arguments
695are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000696the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000697point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000698\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
699yields a result with the same sign as its second operand (or zero);
700the absolute value of the result is strictly smaller than the second
701operand.
Fred Drakef6669171998-05-06 19:52:49 +0000702\index{modulo}
703
704The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000705following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
706modulo are also connected with the built-in function \function{divmod()}:
707\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000708floating point and complex numbers; there similar identities hold
709approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
710\code{floor(x/y) - 1} (for floats),\footnote{
711 If x is very close to an exact integer multiple of y, it's
712 possible for \code{floor(x/y)} to be one larger than
713 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
714 the latter result, in order to preserve that \code{divmod(x,y)[0]
715 * y + x \%{} y} be very close to \code{x}.
716} or \code{floor((x/y).real)} (for
717complex).
Fred Drakef6669171998-05-06 19:52:49 +0000718
Fred Drake5c07d9b1998-05-14 19:37:06 +0000719The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000720The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000721same type. In the former case, the numbers are converted to a common
722type and then added together. In the latter case, the sequences are
723concatenated.
724\index{addition}
725
Fred Drake5c07d9b1998-05-14 19:37:06 +0000726The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000727arguments. The numeric arguments are first converted to a common
728type.
729\index{subtraction}
730
Fred Drake2829f1c2001-06-23 05:27:20 +0000731
Fred Drake020f8c01998-07-28 19:32:59 +0000732\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000733\indexii{shifting}{operation}
734
735The shifting operations have lower priority than the arithmetic
736operations:
737
Fred Drakecb4638a2001-07-06 22:49:53 +0000738\begin{productionlist}
739 \production{shift_expr}
740 {\token{a_expr}
741 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
742\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000743
744These operators accept plain or long integers as arguments. The
745arguments are converted to a common type. They shift the first
746argument to the left or right by the number of bits given by the
747second argument.
748
749A right shift by \var{n} bits is defined as division by
750\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
751multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000752no overflow check so in that case the operation drops bits and flips
753the sign if the result is not less than \code{pow(2,31)} in absolute
754value. Negative shift counts raise a \exception{ValueError}
755exception.
Fred Drakef6669171998-05-06 19:52:49 +0000756\exindex{ValueError}
757
Fred Drake2829f1c2001-06-23 05:27:20 +0000758
Fred Drake020f8c01998-07-28 19:32:59 +0000759\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000760\indexiii{binary}{bit-wise}{operation}
761
762Each of the three bitwise operations has a different priority level:
763
Fred Drakecb4638a2001-07-06 22:49:53 +0000764\begin{productionlist}
765 \production{and_expr}
766 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
767 \production{xor_expr}
768 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
769 \production{or_expr}
770 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
771\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000772
Fred Drake5c07d9b1998-05-14 19:37:06 +0000773The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000774must be plain or long integers. The arguments are converted to a
775common type.
776\indexii{bit-wise}{and}
777
Fred Drake5c07d9b1998-05-14 19:37:06 +0000778The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000779arguments, which must be plain or long integers. The arguments are
780converted to a common type.
781\indexii{bit-wise}{xor}
782\indexii{exclusive}{or}
783
Fred Drake5c07d9b1998-05-14 19:37:06 +0000784The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000785arguments, which must be plain or long integers. The arguments are
786converted to a common type.
787\indexii{bit-wise}{or}
788\indexii{inclusive}{or}
789
Fred Drake2829f1c2001-06-23 05:27:20 +0000790
Fred Drake020f8c01998-07-28 19:32:59 +0000791\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000792\index{comparison}
793
Fred Drake1156f622000-09-19 18:10:05 +0000794Unlike C, all comparison operations in Python have the same priority,
795which is lower than that of any arithmetic, shifting or bitwise
796operation. Also unlike C, expressions like \code{a < b < c} have the
797interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000798\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000799
Fred Drakecb4638a2001-07-06 22:49:53 +0000800\begin{productionlist}
801 \production{comparison}
802 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
803 \production{comp_operator}
804 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
805 | "is" ["not"] | ["not"] "in"}
806\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000807
Fred Drake5c07d9b1998-05-14 19:37:06 +0000808Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000809
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000810Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000811equivalent to \code{x < y and y <= z}, except that \code{y} is
812evaluated only once (but in both cases \code{z} is not evaluated at all
813when \code{x < y} is found to be false).
814\indexii{chaining}{comparisons}
815
816Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
817expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
818operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000819to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000820\var{y opy z}, except that each expression is evaluated at most once.
821
822Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000823between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000824perfectly legal (though perhaps not pretty).
825
Fred Drake5c07d9b1998-05-14 19:37:06 +0000826The forms \code{<>} and \code{!=} are equivalent; for consistency with
827C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000828\code{<>} is also accepted. The \code{<>} spelling is considered
829obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000830
Fred Drake1156f622000-09-19 18:10:05 +0000831The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
832\code{!=} compare
833the values of two objects. The objects need not have the same type.
Fred Drakef6669171998-05-06 19:52:49 +0000834If both are numbers, they are coverted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000835objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000836ordered consistently but arbitrarily.
837
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000838(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000839definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000840\keyword{not in} operators. In the future, the comparison rules for
841objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000842
843Comparison of objects of the same type depends on the type:
844
845\begin{itemize}
846
847\item
848Numbers are compared arithmetically.
849
850\item
851Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000852(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000853characters. Unicode and 8-bit strings are fully interoperable in this
854behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000855
856\item
857Tuples and lists are compared lexicographically using comparison of
858corresponding items.
859
860\item
Tim Peters20524db2001-10-01 20:22:45 +0000861Mappings (dictionaries) compare equal if and only if their sorted
862(key, value) lists compare equal.\footnote{The implementation computes
863 this efficiently, without constructing lists or sorting.}
864Outcomes other than equality are resolved consistently, but are not
Tim Peters1350c072001-10-01 20:25:26 +0000865otherwise defined.\footnote{Earlier versions of Python used
Tim Peters20524db2001-10-01 20:22:45 +0000866 lexicographic comparison of the sorted (key, value) lists, but this
867 was very expensive for the common case of comparing for equality. An
868 even earlier version of Python compared dictionaries by identity only,
869 but this caused surprises because people expected to be able to test
870 a dictionary for emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000871
872\item
873Most other types compare unequal unless they are the same object;
874the choice whether one object is considered smaller or larger than
875another one is made arbitrarily but consistently within one
876execution of a program.
877
878\end{itemize}
879
Fred Drake7399b9e2000-07-11 19:43:47 +0000880The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000881membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
882is a member of the set \var{s}, and false otherwise. \code{\var{x}
883not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
884The set membership test has traditionally been bound to sequences; an
885object is a member of a set if the set is a sequence and contains an
886element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000887to support membership tests without being a sequence. In particular,
888dictionaries support memership testing as a nicer way of spelling
889\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000890
Fred Drake34bafcc2001-01-14 02:57:14 +0000891For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000892only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000893\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000894
Fred Drake1156f622000-09-19 18:10:05 +0000895For the Unicode and string types, \code{\var{x} in \var{y}} is true if
896and only if there exists an index \var{i} such that \code{\var{x} ==
897\var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
898Unicode object of length \code{1}, a \exception{TypeError} exception
899is raised.
Fred Drake7399b9e2000-07-11 19:43:47 +0000900
901For user-defined classes which define the \method{__contains__()} method,
902\code{\var{x} in \var{y}} is true if and only if
903\code{\var{y}.__contains__(\var{x})} is true.
904
905For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000906do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
907and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000908\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
909do not raise \exception{IndexError} exception. (If any other exception
910is raised, it is as if \keyword{in} raised that exception).
911
912The operator \keyword{not in} is defined to have the inverse true value
913of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000914\opindex{in}
915\opindex{not in}
916\indexii{membership}{test}
917\obindex{sequence}
918
Fred Drake5c07d9b1998-05-14 19:37:06 +0000919The operators \keyword{is} and \keyword{is not} test for object identity:
920\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
921are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000922truth value.
923\opindex{is}
924\opindex{is not}
925\indexii{identity}{test}
926
Fred Drake2829f1c2001-06-23 05:27:20 +0000927
Fred Drake020f8c01998-07-28 19:32:59 +0000928\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000929\indexii{Boolean}{operation}
930
931Boolean operations have the lowest priority of all Python operations:
932
Fred Drakecb4638a2001-07-06 22:49:53 +0000933\begin{productionlist}
934 \production{expression}
935 {\token{or_test} | \token{lambda_form}}
936 \production{or_test}
937 {\token{and_test} | \token{or_test} "or" \token{and_test}}
938 \production{and_test}
939 {\token{not_test} | \token{and_test} "and" \token{not_test}}
940 \production{not_test}
941 {\token{comparison} | "not" \token{not_test}}
942 \production{lambda_form}
943 {"lambda" [\token{parameter_list}]: \token{expression}}
944\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000945
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000946In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000947used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000948as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000949(strings, tuples and lists), and empty mappings (dictionaries). All
950other values are interpreted as true.
951
Fred Drake5c07d9b1998-05-14 19:37:06 +0000952The operator \keyword{not} yields \code{1} if its argument is false,
953\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000954\opindex{not}
955
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000956The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000957\var{x} is false, its value is returned; otherwise, \var{y} is
958evaluated and the resulting value is returned.
959\opindex{and}
960
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000961The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000962\var{x} is true, its value is returned; otherwise, \var{y} is
963evaluated and the resulting value is returned.
964\opindex{or}
965
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000966(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000967and type they return to \code{0} and \code{1}, but rather return the
968last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000969This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000970replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000971\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000972invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000973same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000974not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000975
976Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000977expressions. They are a shorthand to create anonymous functions; the
978expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000979yields a function object that behaves virtually identical to one
980defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000981
982\begin{verbatim}
983def name(arguments):
984 return expression
985\end{verbatim}
986
987See section \ref{function} for the syntax of parameter lists. Note
988that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000989\label{lambda}
990\indexii{lambda}{expression}
991\indexii{lambda}{form}
992\indexii{anonmymous}{function}
993
Fred Drake88382692001-06-05 02:17:02 +0000994\strong{Programmer's note:} Prior to Python 2.1, a lambda form defined
995inside a function has no access to names defined in the function's
996namespace. This is because Python had only two scopes: local and
997global. A common work-around was to use default argument values to
998pass selected variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000999
1000\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001001def make_incrementor(increment):
1002 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +00001003\end{verbatim}
1004
Fred Drake88382692001-06-05 02:17:02 +00001005As of Python 2.1, nested scopes were introduced, and this work-around
1006has not been necessary. Python 2.1 supports nested scopes in modules
1007which include the statement \samp{from __future__ import
1008nested_scopes}, and more recent versions of Python enable nested
1009scopes by default. This version works starting with Python 2.1:
1010
1011\begin{verbatim}
1012from __future__ import nested_scopes
1013
1014def make_incrementor(increment):
1015 return lambda x: x+increment
1016\end{verbatim}
1017
1018
Fred Drake020f8c01998-07-28 19:32:59 +00001019\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001020\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +00001021
Fred Drakecb4638a2001-07-06 22:49:53 +00001022\begin{productionlist}
1023 \production{expression_list}
1024 {\token{expression} ( "," \token{expression} )* [","]}
1025\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +00001026
Fred Drakec009d192000-04-25 21:09:10 +00001027An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001028tuple. The length of the tuple is the number of expressions in the
1029list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +00001030\obindex{tuple}
1031
1032The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001033\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +00001034expression without a trailing comma doesn't create a
1035tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +00001036(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +00001037\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001038\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +00001039
Fred Draked09120b1999-04-29 16:43:42 +00001040
Fred Drake020f8c01998-07-28 19:32:59 +00001041\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +00001042
Fred Draked09120b1999-04-29 16:43:42 +00001043The following table summarizes the operator
1044precedences\indexii{operator}{precedence} in Python, from lowest
1045precedence (least binding) to highest precedence (most binding).
1046Operators in the same box have the same precedence. Unless the syntax
1047is explicitly given, operators are binary. Operators in the same box
1048group left to right (except for comparisons, which chain from left to
Fred Drake2a222002000-12-11 22:39:24 +00001049right --- see above, and exponentiation, which groups from right to
1050left).
Fred Drakef6669171998-05-06 19:52:49 +00001051
Fred Draked09120b1999-04-29 16:43:42 +00001052\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001053 \lineii{\keyword{lambda}} {Lambda expression}
1054 \hline
1055 \lineii{\keyword{or}} {Boolean OR}
1056 \hline
1057 \lineii{\keyword{and}} {Boolean AND}
1058 \hline
1059 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1060 \hline
1061 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1062 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1063 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +00001064 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001065 {Comparisons}
1066 \hline
1067 \lineii{\code{|}} {Bitwise OR}
1068 \hline
1069 \lineii{\code{\^}} {Bitwise XOR}
1070 \hline
1071 \lineii{\code{\&}} {Bitwise AND}
1072 \hline
Fred Drake24e7a292001-04-12 12:37:03 +00001073 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001074 \hline
1075 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1076 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001077 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001078 {Multiplication, division, remainder}
1079 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001080 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1081 \lineii{\code{\~\var{x}}} {Bitwise not}
1082 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001083 \lineii{\code{**}} {Exponentiation}
1084 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001085 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1086 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1087 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1088 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001089 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001090 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1091 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1092 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1093 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1094\end{tableii}