blob: c0212d03e1239f415653eeed525675a1b7dbfaf7 [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}
Fred Drake53815882002-03-15 23:21:37 +000057 {\token{parenth_form} | \token{list_display}}
58 \productioncont{| \token{dict_display} | \token{string_conversion}}
Fred Drakecb4638a2001-07-06 22:49:53 +000059\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
Jeremy Hylton53ed9172002-04-01 20:52:24 +000066An identifier occurring as an atom is a name. See Section 4.1 for
67documentation of naming and binding.
Fred Drakef6669171998-05-06 19:52:49 +000068
69When the name is bound to an object, evaluation of the atom yields
70that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000071raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000072\exindex{NameError}
73
Guido van Rossum3a0ad601998-07-23 21:57:42 +000074\strong{Private name mangling:}%
75\indexii{name}{mangling}%
76\indexii{private}{names}%
77when an identifier that textually occurs in a class definition begins
78with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000079underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000080Private names are transformed to a longer form before code is
81generated for them. The transformation inserts the class name in
82front of the name, with leading underscores removed, and a single
83underscore inserted in front of the class name. For example, the
84identifier \code{__spam} occurring in a class named \code{Ham} will be
85transformed to \code{_Ham__spam}. This transformation is independent
86of the syntactical context in which the identifier is used. If the
87transformed name is extremely long (longer than 255 characters),
88implementation defined truncation may happen. If the class name
89consists only of underscores, no transformation is done.
90
Fred Drake2829f1c2001-06-23 05:27:20 +000091
Fred Drake020f8c01998-07-28 19:32:59 +000092\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +000093\index{literal}
94
Guido van Rossum3a0ad601998-07-23 21:57:42 +000095Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +000096
Fred Drakecb4638a2001-07-06 22:49:53 +000097\begin{productionlist}
98 \production{literal}
Fred Drake53815882002-03-15 23:21:37 +000099 {\token{stringliteral} | \token{integer} | \token{longinteger}}
100 \productioncont{| \token{floatnumber} | \token{imagnumber}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000101\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000102
103Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000104integer, long integer, floating point number, complex number) with the
105given value. The value may be approximated in the case of floating
106point and imaginary (complex) literals. See section \ref{literals}
107for details.
Fred Drakef6669171998-05-06 19:52:49 +0000108
109All literals correspond to immutable data types, and hence the
110object's identity is less important than its value. Multiple
111evaluations of literals with the same value (either the same
112occurrence in the program text or a different occurrence) may obtain
113the same object or a different object with the same value.
114\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000115\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000116
Fred Drake2829f1c2001-06-23 05:27:20 +0000117
Fred Drake020f8c01998-07-28 19:32:59 +0000118\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000119\index{parenthesized form}
120
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000121A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000122parentheses:
123
Fred Drakecb4638a2001-07-06 22:49:53 +0000124\begin{productionlist}
125 \production{parenth_form}
126 {"(" [\token{expression_list}] ")"}
127\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000128
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000129A parenthesized expression list yields whatever that expression list
130yields: if the list contains at least one comma, it yields a tuple;
131otherwise, it yields the single expression that makes up the
132expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000133
134An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000135tuples are immutable, the rules for literals apply (i.e., two
136occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000137\indexii{empty}{tuple}
138
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000139Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000140of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000141parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000142in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000143pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000144\index{comma}
145\indexii{tuple}{display}
146
Fred Drake2829f1c2001-06-23 05:27:20 +0000147
Fred Drake020f8c01998-07-28 19:32:59 +0000148\subsection{List displays\label{lists}}
Fred Drakef6669171998-05-06 19:52:49 +0000149\indexii{list}{display}
Skip Montanarob6559392000-09-11 16:31:55 +0000150\indexii{list}{comprehensions}
Fred Drakef6669171998-05-06 19:52:49 +0000151
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000152A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000153square brackets:
154
Fred Drakecb4638a2001-07-06 22:49:53 +0000155\begin{productionlist}
156 \production{list_display}
157 {"[" [\token{listmaker}] "]"}
158 \production{listmaker}
159 {\token{expression} ( \token{list_for}
160 | ( "," \token{expression})* [","] )}
161 \production{list_iter}
162 {\token{list_for} | \token{list_if}}
163 \production{list_for}
164 {"for" \token{expression_list} "in" \token{testlist}
165 [\token{list_iter}]}
166 \production{list_if}
167 {"if" \token{test} [\token{list_iter}]}
168\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000169
Skip Montanaro803d6e52000-08-12 18:09:51 +0000170A list display yields a new list object. Its contents are specified
171by providing either a list of expressions or a list comprehension.
Skip Montanarob6559392000-09-11 16:31:55 +0000172\indexii{list}{comprehensions}
Skip Montanaro803d6e52000-08-12 18:09:51 +0000173When a comma-separated list of expressions is supplied, its elements are
174evaluated from left to right and placed into the list object in that
175order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000176single expression followed by at least one \keyword{for} clause and zero or
Tim Peters20524db2001-10-01 20:22:45 +0000177more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000178case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000179by considering each of the \keyword{for} or \keyword{if} clauses a block,
Tim Peters20524db2001-10-01 20:22:45 +0000180nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000181left to right, and evaluating the expression to produce a list element
182each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000183\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000184\indexii{empty}{list}
185
Fred Drake2829f1c2001-06-23 05:27:20 +0000186
Fred Drake020f8c01998-07-28 19:32:59 +0000187\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000188\indexii{dictionary}{display}
189
190A dictionary display is a possibly empty series of key/datum pairs
191enclosed in curly braces:
192\index{key}
193\index{datum}
194\index{key/datum pair}
195
Fred Drakecb4638a2001-07-06 22:49:53 +0000196\begin{productionlist}
197 \production{dict_display}
Fred Drake83d14c12002-03-16 06:35:54 +0000198 {"\{" [\token{key_datum_list}] "\}"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000199 \production{key_datum_list}
200 {\token{key_datum} ("," \token{key_datum})* [","]}
201 \production{key_datum}
202 {\token{expression} ":" \token{expression}}
203\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000204
205A dictionary display yields a new dictionary object.
206\obindex{dictionary}
207
208The key/datum pairs are evaluated from left to right to define the
209entries of the dictionary: each key object is used as a key into the
210dictionary to store the corresponding datum.
211
212Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000213section \ref{types}. (To summarize,the key type should be hashable,
214which excludes all mutable objects.) Clashes between duplicate keys
215are not detected; the last datum (textually rightmost in the display)
216stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000217\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000218
Fred Drake2829f1c2001-06-23 05:27:20 +0000219
Fred Drake020f8c01998-07-28 19:32:59 +0000220\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000221\indexii{string}{conversion}
222\indexii{reverse}{quotes}
223\indexii{backward}{quotes}
224\index{back-quotes}
225
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000226A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000227backward) quotes:
228
Fred Drakecb4638a2001-07-06 22:49:53 +0000229\begin{productionlist}
230 \production{string_conversion}
231 {"`" \token{expression_list} "`"}
232\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000233
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000234A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000235converts the resulting object into a string according to rules
236specific to its type.
237
Fred Drake5c07d9b1998-05-14 19:37:06 +0000238If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000239dictionary containing only objects whose type is one of these, the
240resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000241the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000242same value (or an approximation, if floating point numbers are
243involved).
244
245(In particular, converting a string adds quotes around it and converts
246``funny'' characters to escape sequences that are safe to print.)
247
Fred Drakece5619e2002-11-13 15:32:34 +0000248Recursive objects (for example, lists or dictionaries that contain a
249reference to themselves, directly or indirectly) use \samp{...} to
250indicate a recursive reference, and the result cannot be passed to
251\function{eval()} to get an equal value (\exception{SyntaxError} will
252be raised instead).
Fred Drakef6669171998-05-06 19:52:49 +0000253\obindex{recursive}
254
Fred Drake5c07d9b1998-05-14 19:37:06 +0000255The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000256conversion in its argument as enclosing it in parentheses and reverse
257quotes does. The built-in function \function{str()} performs a
258similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000259\bifuncindex{repr}
260\bifuncindex{str}
261
Fred Drake2829f1c2001-06-23 05:27:20 +0000262
Fred Drake020f8c01998-07-28 19:32:59 +0000263\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000264\index{primary}
265
266Primaries represent the most tightly bound operations of the language.
267Their syntax is:
268
Fred Drakecb4638a2001-07-06 22:49:53 +0000269\begin{productionlist}
270 \production{primary}
271 {\token{atom} | \token{attributeref}
272 | \token{subscription} | \token{slicing} | \token{call}}
273\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000274
Fred Drake2829f1c2001-06-23 05:27:20 +0000275
Fred Drake020f8c01998-07-28 19:32:59 +0000276\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000277\indexii{attribute}{reference}
278
279An attribute reference is a primary followed by a period and a name:
280
Fred Drakecb4638a2001-07-06 22:49:53 +0000281\begin{productionlist}
282 \production{attributeref}
283 {\token{primary} "." \token{identifier}}
284\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000285
286The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000287attribute references, e.g., a module, list, or an instance. This
288object is then asked to produce the attribute whose name is the
289identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000290\exception{AttributeError}\exindex{AttributeError} is raised.
291Otherwise, the type and value of the object produced is determined by
292the object. Multiple evaluations of the same attribute reference may
293yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000294\obindex{module}
295\obindex{list}
296
Fred Drake2829f1c2001-06-23 05:27:20 +0000297
Fred Drake020f8c01998-07-28 19:32:59 +0000298\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000299\index{subscription}
300
301A subscription selects an item of a sequence (string, tuple or list)
302or mapping (dictionary) object:
303\obindex{sequence}
304\obindex{mapping}
305\obindex{string}
306\obindex{tuple}
307\obindex{list}
308\obindex{dictionary}
309\indexii{sequence}{item}
310
Fred Drakecb4638a2001-07-06 22:49:53 +0000311\begin{productionlist}
312 \production{subscription}
313 {\token{primary} "[" \token{expression_list} "]"}
314\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000315
316The primary must evaluate to an object of a sequence or mapping type.
317
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000318If the primary is a mapping, the expression list must evaluate to an
319object whose value is one of the keys of the mapping, and the
320subscription selects the value in the mapping that corresponds to that
321key. (The expression list is a tuple except if it has exactly one
322item.)
Fred Drakef6669171998-05-06 19:52:49 +0000323
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000324If the primary is a sequence, the expression (list) must evaluate to a
325plain integer. If this value is negative, the length of the sequence
326is added to it (so that, e.g., \code{x[-1]} selects the last item of
327\code{x}.) The resulting value must be a nonnegative integer less
328than the number of items in the sequence, and the subscription selects
329the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000330
331A string's items are characters. A character is not a separate data
332type but a string of exactly one character.
333\index{character}
334\indexii{string}{item}
335
Fred Drake2829f1c2001-06-23 05:27:20 +0000336
Fred Drake020f8c01998-07-28 19:32:59 +0000337\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000338\index{slicing}
339\index{slice}
340
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000341A slicing selects a range of items in a sequence object (e.g., a
342string, tuple or list). Slicings may be used as expressions or as
343targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000344\obindex{sequence}
345\obindex{string}
346\obindex{tuple}
347\obindex{list}
348
Fred Drakecb4638a2001-07-06 22:49:53 +0000349\begin{productionlist}
350 \production{slicing}
351 {\token{simple_slicing} | \token{extended_slicing}}
352 \production{simple_slicing}
353 {\token{primary} "[" \token{short_slice} "]"}
354 \production{extended_slicing}
355 {\token{primary} "[" \token{slice_list} "]" }
356 \production{slice_list}
357 {\token{slice_item} ("," \token{slice_item})* [","]}
358 \production{slice_item}
359 {\token{expression} | \token{proper_slice} | \token{ellipsis}}
360 \production{proper_slice}
361 {\token{short_slice} | \token{long_slice}}
362 \production{short_slice}
363 {[\token{lower_bound}] ":" [\token{upper_bound}]}
364 \production{long_slice}
365 {\token{short_slice} ":" [\token{stride}]}
366 \production{lower_bound}
367 {\token{expression}}
368 \production{upper_bound}
369 {\token{expression}}
370 \production{stride}
371 {\token{expression}}
372 \production{ellipsis}
373 {"..."}
374\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000375
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000376There is ambiguity in the formal syntax here: anything that looks like
377an expression list also looks like a slice list, so any subscription
378can be interpreted as a slicing. Rather than further complicating the
379syntax, this is disambiguated by defining that in this case the
380interpretation as a subscription takes priority over the
381interpretation as a slicing (this is the case if the slice list
382contains no proper slice nor ellipses). Similarly, when the slice
383list has exactly one short slice and no trailing comma, the
384interpretation as a simple slicing takes priority over that as an
385extended slicing.\indexii{extended}{slicing}
386
387The semantics for a simple slicing are as follows. The primary must
388evaluate to a sequence object. The lower and upper bound expressions,
389if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000390\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000391sequence's length is added to it. The slicing now selects all items
392with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000393\code{\var{i} <= \var{k} < \var{j}} where \var{i}
394and \var{j} are the specified lower and upper bounds. This may be an
395empty sequence. It is not an error if \var{i} or \var{j} lie outside the
396range of valid indexes (such items don't exist so they aren't
397selected).
398
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000399The semantics for an extended slicing are as follows. The primary
400must evaluate to a mapping object, and it is indexed with a key that
401is constructed from the slice list, as follows. If the slice list
402contains at least one comma, the key is a tuple containing the
403conversion of the slice items; otherwise, the conversion of the lone
404slice item is the key. The conversion of a slice item that is an
405expression is that expression. The conversion of an ellipsis slice
406item is the built-in \code{Ellipsis} object. The conversion of a
407proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000408\member{start}, \member{stop} and \member{step} attributes are the
409values of the expressions given as lower bound, upper bound and
410stride, respectively, substituting \code{None} for missing
411expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000412\withsubitem{(slice object attribute)}{\ttindex{start}
413 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000414
Fred Drake2829f1c2001-06-23 05:27:20 +0000415
Fred Drake020f8c01998-07-28 19:32:59 +0000416\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000417\index{call}
418
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000419A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000420series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000421\obindex{callable}
422
Fred Drakecb4638a2001-07-06 22:49:53 +0000423\begin{productionlist}
424 \production{call}
425 {\token{primary} "(" [\token{argument_list} [","]] ")"}
426 \production{argument_list}
Fred Drake74653822002-10-07 16:28:38 +0000427 {\token{positional_arguments} ["," \token{keyword_arguments}]}
428 \productioncont{ ["," "*" \token{expression}]}
429 \productioncont{ ["," "**" \token{expression}]}
430 \productioncont{| \token{keyword_arguments} ["," "*" \token{expression}]}
431 \productioncont{ ["," "**" \token{expression}]}
Fred Drake53815882002-03-15 23:21:37 +0000432 \productioncont{| "*" \token{expression} ["," "**" \token{expression}]}
433 \productioncont{| "**" \token{expression}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000434 \production{positional_arguments}
435 {\token{expression} ("," \token{expression})*}
436 \production{keyword_arguments}
437 {\token{keyword_item} ("," \token{keyword_item})*}
438 \production{keyword_item}
439 {\token{identifier} "=" \token{expression}}
440\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000441
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000442A trailing comma may be present after an argument list but does not
443affect the semantics.
444
Fred Drakef6669171998-05-06 19:52:49 +0000445The primary must evaluate to a callable object (user-defined
446functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000447objects, methods of class instances, and certain class instances
448themselves are callable; extensions may define additional callable
449object types). All argument expressions are evaluated before the call
450is attempted. Please refer to section \ref{function} for the syntax
451of formal parameter lists.
452
453If keyword arguments are present, they are first converted to
454positional arguments, as follows. First, a list of unfilled slots is
455created for the formal parameters. If there are N positional
456arguments, they are placed in the first N slots. Next, for each
457keyword argument, the identifier is used to determine the
458corresponding slot (if the identifier is the same as the first formal
459parameter name, the first slot is used, and so on). If the slot is
460already filled, a \exception{TypeError} exception is raised.
461Otherwise, the value of the argument is placed in the slot, filling it
462(even if the expression is \code{None}, it fills the slot). When all
463arguments have been processed, the slots that are still unfilled are
464filled with the corresponding default value from the function
465definition. (Default values are calculated, once, when the function
466is defined; thus, a mutable object such as a list or dictionary used
467as default value will be shared by all calls that don't specify an
468argument value for the corresponding slot; this should usually be
469avoided.) If there are any unfilled slots for which no default value
470is specified, a \exception{TypeError} exception is raised. Otherwise,
471the list of filled slots is used as the argument list for the call.
472
473If there are more positional arguments than there are formal parameter
474slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000475parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000476case, that formal parameter receives a tuple containing the excess
477positional arguments (or an empty tuple if there were no excess
478positional arguments).
479
480If any keyword argument does not correspond to a formal parameter
481name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000482parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000483case, that formal parameter receives a dictionary containing the
484excess keyword arguments (using the keywords as keys and the argument
485values as corresponding values), or a (new) empty dictionary if there
486were no excess keyword arguments.
487
Michael W. Hudson850d3982001-12-12 11:56:33 +0000488If the syntax \samp{*expression} appears in the function call,
489\samp{expression} must evaluate to a sequence. Elements from this
490sequence are treated as if they were additional positional arguments;
491if there are postional arguments \var{x1},...,\var{xN} , and
492\samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
493is equivalent to a call with M+N positional arguments
494\var{x1},...,\var{xN},\var{y1},...,\var{yM}.
495
496A consequence of this is that although the \samp{*expression} syntax
497appears \emph{after} any keyword arguments, it is processed
Fred Drakeb062cb22001-12-14 16:57:31 +0000498\emph{before} the keyword arguments (and the
499\samp{**expression} argument, if any -- see below). So:
Michael W. Hudson850d3982001-12-12 11:56:33 +0000500
501\begin{verbatim}
502>>> def f(a, b):
503... print a, b
504...
505>>> f(b=1, *(2,))
5062 1
507>>> f(a=1, *(2,))
508Traceback (most recent call last):
509 File "<stdin>", line 1, in ?
510TypeError: f() got multiple values for keyword argument 'a'
511>>> f(1, *(2,))
5121 2
513\end{verbatim}
514
Fred Drakeb062cb22001-12-14 16:57:31 +0000515It is unusual for both keyword arguments and the
516\samp{*expression} syntax to be used in the same call, so in practice
517this confusion does not arise.
Michael W. Hudson850d3982001-12-12 11:56:33 +0000518
519If the syntax \samp{**expression} appears in the function call,
520\samp{expression} must evaluate to a (subclass of) dictionary, the
521contents of which are treated as additional keyword arguments. In the
522case of a keyword appearing in both \samp{expression} and as an
523explicit keyword argument, a \exception{TypeError} exception is
524raised.
525
Fred Drakeea81edf1998-11-25 17:51:15 +0000526Formal parameters using the syntax \samp{*identifier} or
527\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000528as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000529\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000530outermost sublist corresponds to a single unnamed argument slot, and
531the argument value is assigned to the sublist using the usual tuple
532assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000533
Fred Drake5c07d9b1998-05-14 19:37:06 +0000534A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000535raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000536of the callable object.
537
538If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000539
540\begin{description}
541
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000542\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000543executed, passing it the argument list. The first thing the code
544block will do is bind the formal parameters to the arguments; this is
545described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000546\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000547function call.
548\indexii{function}{call}
549\indexiii{user-defined}{function}{call}
550\obindex{user-defined function}
551\obindex{function}
552
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000553\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000554interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
555Library Reference} for the descriptions of built-in functions and
556methods.
Fred Drakef6669171998-05-06 19:52:49 +0000557\indexii{function}{call}
558\indexii{built-in function}{call}
559\indexii{method}{call}
560\indexii{built-in method}{call}
561\obindex{built-in method}
562\obindex{built-in function}
563\obindex{method}
564\obindex{function}
565
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000566\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000567\obindex{class}
568\indexii{class object}{call}
569
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000570\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000571function is called, with an argument list that is one longer than the
572argument list of the call: the instance becomes the first argument.
573\obindex{class instance}
574\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000575\indexii{class instance}{call}
576
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000577\item[a class instance:] The class must define a \method{__call__()}
578method; the effect is then the same as if that method was called.
579\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000580\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000581
Fred Drakef6669171998-05-06 19:52:49 +0000582\end{description}
583
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000584
Fred Drake020f8c01998-07-28 19:32:59 +0000585\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000586
587The power operator binds more tightly than unary operators on its
588left; it binds less tightly than unary operators on its right. The
589syntax is:
590
Fred Drakecb4638a2001-07-06 22:49:53 +0000591\begin{productionlist}
592 \production{power}
593 {\token{primary} ["**" \token{u_expr}]}
594\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000595
596Thus, in an unparenthesized sequence of power and unary operators, the
597operators are evaluated from right to left (this does not constrain
598the evaluation order for the operands).
599
600The power operator has the same semantics as the built-in
601\function{pow()} function, when called with two arguments: it yields
602its left argument raised to the power of its right argument. The
603numeric arguments are first converted to a common type. The result
Raymond Hettinger0da7f392002-11-08 05:30:23 +0000604type is that of the arguments after coercion.
605
606With mixed operand types, the coercion rules for binary arithmetic
607operators apply. For int and long int operands, the result has the
608same type as the operands (after coercion) unless the second argument
609is negative; in that case, all arguments are converted to float and a
610float result is delivered. For example, \code{10**2} returns \code{100},
611but \code{10**-2} returns \code{0.01}. (This last feature was added in
612Python 2.2. In Python 2.1 and before, if both arguments were of integer
613types and the second argument was negative, an exception was raised).
614
615Raising \code{0.0} to a negative power results in a
616\exception{ZeroDivisionError}. Raising a negative number to a
617fractional power results in a \exception{ValueError}.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000618
619
Fred Drakee15956b2000-04-03 04:51:13 +0000620\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000621\indexiii{unary}{arithmetic}{operation}
622\indexiii{unary}{bit-wise}{operation}
623
624All unary arithmetic (and bit-wise) operations have the same priority:
625
Fred Drakecb4638a2001-07-06 22:49:53 +0000626\begin{productionlist}
627 \production{u_expr}
628 {\token{power} | "-" \token{u_expr}
Fred Drakef6eafc32002-03-18 16:47:14 +0000629 | "+" \token{u_expr} | "{\~}" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000630\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000631
Fred Drake5c07d9b1998-05-14 19:37:06 +0000632The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000633numeric argument.
634\index{negation}
635\index{minus}
636
Fred Drake5c07d9b1998-05-14 19:37:06 +0000637The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000638unchanged.
639\index{plus}
640
Fred Drakee15956b2000-04-03 04:51:13 +0000641The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000642of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000643\code{x} is defined as \code{-(x+1)}. It only applies to integral
644numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000645\index{inversion}
646
647In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000648a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000649\exindex{TypeError}
650
Fred Drake2829f1c2001-06-23 05:27:20 +0000651
Fred Drake020f8c01998-07-28 19:32:59 +0000652\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000653\indexiii{binary}{arithmetic}{operation}
654
655The binary arithmetic operations have the conventional priority
656levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000657non-numeric types. Apart from the power operator, there are only two
658levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000659operators:
660
Fred Drakecb4638a2001-07-06 22:49:53 +0000661\begin{productionlist}
662 \production{m_expr}
663 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000664 | \token{m_expr} "//" \token{u_expr}
Fred Drake53815882002-03-15 23:21:37 +0000665 | \token{m_expr} "/" \token{u_expr}}
666 \productioncont{| \token{m_expr} "\%" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000667 \production{a_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000668 {\token{m_expr} | \token{a_expr} "+" \token{m_expr}
669 | \token{a_expr} "-" \token{m_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000670\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000671
Fred Drake5c07d9b1998-05-14 19:37:06 +0000672The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000673arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000674must be an integer (plain or long) and the other must be a sequence.
675In the former case, the numbers are converted to a common type and
676then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000677performed; a negative repetition factor yields an empty sequence.
678\index{multiplication}
679
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000680The \code{/} (division) and \code{//} (floor division) operators yield
681the quotient of their arguments. The numeric arguments are first
682converted to a common type. Plain or long integer division yields an
683integer of the same type; the result is that of mathematical division
684with the `floor' function applied to the result. Division by zero
685raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000686\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000687\exindex{ZeroDivisionError}
688\index{division}
689
Fred Drake5c07d9b1998-05-14 19:37:06 +0000690The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000691division of the first argument by the second. The numeric arguments
692are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000693the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000694point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000695\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
696yields a result with the same sign as its second operand (or zero);
Tim Peters5b21df42002-11-24 20:23:04 +0000697the absolute value of the result is strictly smaller than the absolute
698value of the second operand\footnote{
Gustavo Niemeyerf9554122002-11-26 18:14:35 +0000699 While \code{abs(x\%y) < abs(y)} is true mathematically, for
Tim Peters5b21df42002-11-24 20:23:04 +0000700 floats it may not be true numerically due to roundoff. For
701 example, and assuming a platform on which a Python float is an
702 IEEE 754 double-precision number, in order that \code{-1e-100 \% 1e100}
703 have the same sign as \code{1e100}, the computed result is
704 \code{-1e-100 + 1e100}, which is numerically exactly equal
705 to \code{1e100}. Function \function{fmod()} in the \module{math}
706 module returns a result whose sign matches the sign of the
707 first argument instead, and so returns \code{-1e-100} in this case.
708 Which approach is more appropriate depends on the application.
709}.
Fred Drakef6669171998-05-06 19:52:49 +0000710\index{modulo}
711
712The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000713following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
714modulo are also connected with the built-in function \function{divmod()}:
715\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000716floating point numbers; there similar identities hold
Fred Drake1ea7c751999-05-06 14:46:35 +0000717approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
Tim Peters5b21df42002-11-24 20:23:04 +0000718\code{floor(x/y) - 1}\footnote{
Fred Drake1ea7c751999-05-06 14:46:35 +0000719 If x is very close to an exact integer multiple of y, it's
720 possible for \code{floor(x/y)} to be one larger than
721 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
722 the latter result, in order to preserve that \code{divmod(x,y)[0]
723 * y + x \%{} y} be very close to \code{x}.
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000724}.
725
Raymond Hettinger463bfaf2002-10-11 21:08:02 +0000726\deprecated{2.3}{The floor division operator, the modulo operator,
727and the \function{divmod()} function are no longer defined for complex
728numbers. Instead, convert to a floating point number using the
729\function{abs()} function if appropriate.}
Fred Drakef6669171998-05-06 19:52:49 +0000730
Fred Drake5c07d9b1998-05-14 19:37:06 +0000731The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000732The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000733same type. In the former case, the numbers are converted to a common
734type and then added together. In the latter case, the sequences are
735concatenated.
736\index{addition}
737
Fred Drake5c07d9b1998-05-14 19:37:06 +0000738The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000739arguments. The numeric arguments are first converted to a common
740type.
741\index{subtraction}
742
Fred Drake2829f1c2001-06-23 05:27:20 +0000743
Fred Drake020f8c01998-07-28 19:32:59 +0000744\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000745\indexii{shifting}{operation}
746
747The shifting operations have lower priority than the arithmetic
748operations:
749
Fred Drakecb4638a2001-07-06 22:49:53 +0000750\begin{productionlist}
751 \production{shift_expr}
752 {\token{a_expr}
753 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
754\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000755
756These operators accept plain or long integers as arguments. The
757arguments are converted to a common type. They shift the first
758argument to the left or right by the number of bits given by the
759second argument.
760
761A right shift by \var{n} bits is defined as division by
762\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
763multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000764no overflow check so in that case the operation drops bits and flips
765the sign if the result is not less than \code{pow(2,31)} in absolute
766value. Negative shift counts raise a \exception{ValueError}
767exception.
Fred Drakef6669171998-05-06 19:52:49 +0000768\exindex{ValueError}
769
Fred Drake2829f1c2001-06-23 05:27:20 +0000770
Fred Drake020f8c01998-07-28 19:32:59 +0000771\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000772\indexiii{binary}{bit-wise}{operation}
773
774Each of the three bitwise operations has a different priority level:
775
Fred Drakecb4638a2001-07-06 22:49:53 +0000776\begin{productionlist}
777 \production{and_expr}
778 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
779 \production{xor_expr}
780 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
781 \production{or_expr}
782 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
783\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000784
Fred Drake5c07d9b1998-05-14 19:37:06 +0000785The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000786must be plain or long integers. The arguments are converted to a
787common type.
788\indexii{bit-wise}{and}
789
Fred Drake5c07d9b1998-05-14 19:37:06 +0000790The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000791arguments, which must be plain or long integers. The arguments are
792converted to a common type.
793\indexii{bit-wise}{xor}
794\indexii{exclusive}{or}
795
Fred Drake5c07d9b1998-05-14 19:37:06 +0000796The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000797arguments, which must be plain or long integers. The arguments are
798converted to a common type.
799\indexii{bit-wise}{or}
800\indexii{inclusive}{or}
801
Fred Drake2829f1c2001-06-23 05:27:20 +0000802
Fred Drake020f8c01998-07-28 19:32:59 +0000803\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000804\index{comparison}
805
Fred Drake1156f622000-09-19 18:10:05 +0000806Unlike C, all comparison operations in Python have the same priority,
807which is lower than that of any arithmetic, shifting or bitwise
808operation. Also unlike C, expressions like \code{a < b < c} have the
809interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000810\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000811
Fred Drakecb4638a2001-07-06 22:49:53 +0000812\begin{productionlist}
813 \production{comparison}
814 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
815 \production{comp_operator}
Fred Drake53815882002-03-15 23:21:37 +0000816 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="}
817 \productioncont{| "is" ["not"] | ["not"] "in"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000818\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000819
Fred Drake5c07d9b1998-05-14 19:37:06 +0000820Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000821
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000822Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000823equivalent to \code{x < y and y <= z}, except that \code{y} is
824evaluated only once (but in both cases \code{z} is not evaluated at all
825when \code{x < y} is found to be false).
826\indexii{chaining}{comparisons}
827
828Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
829expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
830operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000831to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000832\var{y opy z}, except that each expression is evaluated at most once.
833
834Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000835between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000836perfectly legal (though perhaps not pretty).
837
Fred Drake5c07d9b1998-05-14 19:37:06 +0000838The forms \code{<>} and \code{!=} are equivalent; for consistency with
839C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000840\code{<>} is also accepted. The \code{<>} spelling is considered
841obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000842
Fred Drake1156f622000-09-19 18:10:05 +0000843The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
844\code{!=} compare
845the values of two objects. The objects need not have the same type.
Fred Drakefd867712002-04-09 14:39:10 +0000846If both are numbers, they are converted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000847objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000848ordered consistently but arbitrarily.
849
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000850(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000851definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000852\keyword{not in} operators. In the future, the comparison rules for
853objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000854
855Comparison of objects of the same type depends on the type:
856
857\begin{itemize}
858
859\item
860Numbers are compared arithmetically.
861
862\item
863Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000864(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000865characters. Unicode and 8-bit strings are fully interoperable in this
866behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000867
868\item
869Tuples and lists are compared lexicographically using comparison of
870corresponding items.
871
872\item
Tim Peters20524db2001-10-01 20:22:45 +0000873Mappings (dictionaries) compare equal if and only if their sorted
874(key, value) lists compare equal.\footnote{The implementation computes
875 this efficiently, without constructing lists or sorting.}
876Outcomes other than equality are resolved consistently, but are not
Tim Peters1350c072001-10-01 20:25:26 +0000877otherwise defined.\footnote{Earlier versions of Python used
Tim Peters20524db2001-10-01 20:22:45 +0000878 lexicographic comparison of the sorted (key, value) lists, but this
879 was very expensive for the common case of comparing for equality. An
880 even earlier version of Python compared dictionaries by identity only,
881 but this caused surprises because people expected to be able to test
882 a dictionary for emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000883
884\item
885Most other types compare unequal unless they are the same object;
886the choice whether one object is considered smaller or larger than
887another one is made arbitrarily but consistently within one
888execution of a program.
889
890\end{itemize}
891
Fred Drake7399b9e2000-07-11 19:43:47 +0000892The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000893membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
894is a member of the set \var{s}, and false otherwise. \code{\var{x}
895not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
896The set membership test has traditionally been bound to sequences; an
897object is a member of a set if the set is a sequence and contains an
898element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000899to support membership tests without being a sequence. In particular,
900dictionaries support memership testing as a nicer way of spelling
901\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000902
Fred Drake34bafcc2001-01-14 02:57:14 +0000903For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000904only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000905\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000906
Fred Drake1156f622000-09-19 18:10:05 +0000907For the Unicode and string types, \code{\var{x} in \var{y}} is true if
908and only if there exists an index \var{i} such that \code{\var{x} ==
909\var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
910Unicode object of length \code{1}, a \exception{TypeError} exception
911is raised.
Fred Drake7399b9e2000-07-11 19:43:47 +0000912
913For user-defined classes which define the \method{__contains__()} method,
914\code{\var{x} in \var{y}} is true if and only if
915\code{\var{y}.__contains__(\var{x})} is true.
916
917For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000918do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
919and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000920\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
921do not raise \exception{IndexError} exception. (If any other exception
922is raised, it is as if \keyword{in} raised that exception).
923
924The operator \keyword{not in} is defined to have the inverse true value
925of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000926\opindex{in}
927\opindex{not in}
928\indexii{membership}{test}
929\obindex{sequence}
930
Fred Drake5c07d9b1998-05-14 19:37:06 +0000931The operators \keyword{is} and \keyword{is not} test for object identity:
932\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
933are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000934truth value.
935\opindex{is}
936\opindex{is not}
937\indexii{identity}{test}
938
Fred Drake2829f1c2001-06-23 05:27:20 +0000939
Fred Drake020f8c01998-07-28 19:32:59 +0000940\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000941\indexii{Boolean}{operation}
942
943Boolean operations have the lowest priority of all Python operations:
944
Fred Drakecb4638a2001-07-06 22:49:53 +0000945\begin{productionlist}
946 \production{expression}
947 {\token{or_test} | \token{lambda_form}}
948 \production{or_test}
949 {\token{and_test} | \token{or_test} "or" \token{and_test}}
950 \production{and_test}
951 {\token{not_test} | \token{and_test} "and" \token{not_test}}
952 \production{not_test}
953 {\token{comparison} | "not" \token{not_test}}
954 \production{lambda_form}
955 {"lambda" [\token{parameter_list}]: \token{expression}}
956\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000957
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000958In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000959used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000960as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000961(strings, tuples and lists), and empty mappings (dictionaries). All
962other values are interpreted as true.
963
Fred Drake5c07d9b1998-05-14 19:37:06 +0000964The operator \keyword{not} yields \code{1} if its argument is false,
965\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000966\opindex{not}
967
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000968The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000969\var{x} is false, its value is returned; otherwise, \var{y} is
970evaluated and the resulting value is returned.
971\opindex{and}
972
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000973The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000974\var{x} is true, its value is returned; otherwise, \var{y} is
975evaluated and the resulting value is returned.
976\opindex{or}
977
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000978(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000979and type they return to \code{0} and \code{1}, but rather return the
980last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000981This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000982replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000983\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000984invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000985same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000986not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000987
Jeremy Hylton2225add2002-04-01 21:05:21 +0000988\section{Lambdas\label{lambdas}}
989\indexii{lambda}{expression}
990\indexii{lambda}{form}
991\indexii{anonmymous}{function}
992
Fred Drakef6669171998-05-06 19:52:49 +0000993Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000994expressions. They are a shorthand to create anonymous functions; the
995expression \code{lambda \var{arguments}: \var{expression}}
Jeremy Hylton2225add2002-04-01 21:05:21 +0000996yields a function object. The unnamed object behaves like a function
Raymond Hettinger7fd9ced2002-06-25 04:04:14 +0000997object defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000998
999\begin{verbatim}
1000def name(arguments):
1001 return expression
1002\end{verbatim}
1003
1004See section \ref{function} for the syntax of parameter lists. Note
1005that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +00001006\label{lambda}
Fred Drake88382692001-06-05 02:17:02 +00001007
Fred Drake020f8c01998-07-28 19:32:59 +00001008\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001009\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +00001010
Fred Drakecb4638a2001-07-06 22:49:53 +00001011\begin{productionlist}
1012 \production{expression_list}
1013 {\token{expression} ( "," \token{expression} )* [","]}
1014\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +00001015
Fred Drakec009d192000-04-25 21:09:10 +00001016An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001017tuple. The length of the tuple is the number of expressions in the
1018list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +00001019\obindex{tuple}
1020
1021The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001022\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +00001023expression without a trailing comma doesn't create a
1024tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +00001025(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +00001026\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001027\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +00001028
Gustavo Niemeyer78429a62002-12-16 13:54:02 +00001029\section{Evaluation order\label{evalorder}}
1030\indexii{evaluation}{order}
1031
1032Python evaluates expressions from left to right. Notice that while
1033evaluating an assignment, the right-hand side is evaluated before
1034the left-hand side.
1035
1036In the following lines, expressions will be evaluated in the
1037arithmetic order of their suffixes:
1038
1039\begin{verbatim}
1040expr1, expr2, expr3, expr4
1041(expr1, expr2, expr3, expr4)
1042{expr1: expr2, expr3: expr4}
1043expr1 + expr2 * (expr3 - expr4)
1044func(expr1, expr2, *expr3, **expr4)
1045expr3, expr4 = expr1, expr2
1046\end{verbatim}
Fred Draked09120b1999-04-29 16:43:42 +00001047
Fred Drake020f8c01998-07-28 19:32:59 +00001048\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +00001049
Fred Draked09120b1999-04-29 16:43:42 +00001050The following table summarizes the operator
1051precedences\indexii{operator}{precedence} in Python, from lowest
1052precedence (least binding) to highest precedence (most binding).
1053Operators in the same box have the same precedence. Unless the syntax
1054is explicitly given, operators are binary. Operators in the same box
1055group left to right (except for comparisons, which chain from left to
Fred Drake2a222002000-12-11 22:39:24 +00001056right --- see above, and exponentiation, which groups from right to
1057left).
Fred Drakef6669171998-05-06 19:52:49 +00001058
Fred Draked09120b1999-04-29 16:43:42 +00001059\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001060 \lineii{\keyword{lambda}} {Lambda expression}
1061 \hline
1062 \lineii{\keyword{or}} {Boolean OR}
1063 \hline
1064 \lineii{\keyword{and}} {Boolean AND}
1065 \hline
1066 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1067 \hline
1068 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1069 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1070 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +00001071 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001072 {Comparisons}
1073 \hline
1074 \lineii{\code{|}} {Bitwise OR}
1075 \hline
1076 \lineii{\code{\^}} {Bitwise XOR}
1077 \hline
1078 \lineii{\code{\&}} {Bitwise AND}
1079 \hline
Fred Drake24e7a292001-04-12 12:37:03 +00001080 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001081 \hline
1082 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1083 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001084 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001085 {Multiplication, division, remainder}
1086 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001087 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1088 \lineii{\code{\~\var{x}}} {Bitwise not}
1089 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001090 \lineii{\code{**}} {Exponentiation}
1091 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001092 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1093 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1094 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1095 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001096 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001097 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1098 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1099 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1100 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1101\end{tableii}