blob: 6e28fab7a42df740a01aaa8c3abf59a7fdaa6780 [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
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000248It is illegal to attempt to convert recursive objects (e.g., lists or
Fred Drakef6669171998-05-06 19:52:49 +0000249dictionaries that contain a reference to themselves, directly or
250indirectly.)
251\obindex{recursive}
252
Fred Drake5c07d9b1998-05-14 19:37:06 +0000253The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000254conversion in its argument as enclosing it in parentheses and reverse
255quotes does. The built-in function \function{str()} performs a
256similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000257\bifuncindex{repr}
258\bifuncindex{str}
259
Fred Drake2829f1c2001-06-23 05:27:20 +0000260
Fred Drake020f8c01998-07-28 19:32:59 +0000261\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000262\index{primary}
263
264Primaries represent the most tightly bound operations of the language.
265Their syntax is:
266
Fred Drakecb4638a2001-07-06 22:49:53 +0000267\begin{productionlist}
268 \production{primary}
269 {\token{atom} | \token{attributeref}
270 | \token{subscription} | \token{slicing} | \token{call}}
271\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000272
Fred Drake2829f1c2001-06-23 05:27:20 +0000273
Fred Drake020f8c01998-07-28 19:32:59 +0000274\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000275\indexii{attribute}{reference}
276
277An attribute reference is a primary followed by a period and a name:
278
Fred Drakecb4638a2001-07-06 22:49:53 +0000279\begin{productionlist}
280 \production{attributeref}
281 {\token{primary} "." \token{identifier}}
282\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000283
284The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000285attribute references, e.g., a module, list, or an instance. This
286object is then asked to produce the attribute whose name is the
287identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000288\exception{AttributeError}\exindex{AttributeError} is raised.
289Otherwise, the type and value of the object produced is determined by
290the object. Multiple evaluations of the same attribute reference may
291yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000292\obindex{module}
293\obindex{list}
294
Fred Drake2829f1c2001-06-23 05:27:20 +0000295
Fred Drake020f8c01998-07-28 19:32:59 +0000296\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000297\index{subscription}
298
299A subscription selects an item of a sequence (string, tuple or list)
300or mapping (dictionary) object:
301\obindex{sequence}
302\obindex{mapping}
303\obindex{string}
304\obindex{tuple}
305\obindex{list}
306\obindex{dictionary}
307\indexii{sequence}{item}
308
Fred Drakecb4638a2001-07-06 22:49:53 +0000309\begin{productionlist}
310 \production{subscription}
311 {\token{primary} "[" \token{expression_list} "]"}
312\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000313
314The primary must evaluate to an object of a sequence or mapping type.
315
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000316If the primary is a mapping, the expression list must evaluate to an
317object whose value is one of the keys of the mapping, and the
318subscription selects the value in the mapping that corresponds to that
319key. (The expression list is a tuple except if it has exactly one
320item.)
Fred Drakef6669171998-05-06 19:52:49 +0000321
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000322If the primary is a sequence, the expression (list) must evaluate to a
323plain integer. If this value is negative, the length of the sequence
324is added to it (so that, e.g., \code{x[-1]} selects the last item of
325\code{x}.) The resulting value must be a nonnegative integer less
326than the number of items in the sequence, and the subscription selects
327the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000328
329A string's items are characters. A character is not a separate data
330type but a string of exactly one character.
331\index{character}
332\indexii{string}{item}
333
Fred Drake2829f1c2001-06-23 05:27:20 +0000334
Fred Drake020f8c01998-07-28 19:32:59 +0000335\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000336\index{slicing}
337\index{slice}
338
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000339A slicing selects a range of items in a sequence object (e.g., a
340string, tuple or list). Slicings may be used as expressions or as
341targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000342\obindex{sequence}
343\obindex{string}
344\obindex{tuple}
345\obindex{list}
346
Fred Drakecb4638a2001-07-06 22:49:53 +0000347\begin{productionlist}
348 \production{slicing}
349 {\token{simple_slicing} | \token{extended_slicing}}
350 \production{simple_slicing}
351 {\token{primary} "[" \token{short_slice} "]"}
352 \production{extended_slicing}
353 {\token{primary} "[" \token{slice_list} "]" }
354 \production{slice_list}
355 {\token{slice_item} ("," \token{slice_item})* [","]}
356 \production{slice_item}
357 {\token{expression} | \token{proper_slice} | \token{ellipsis}}
358 \production{proper_slice}
359 {\token{short_slice} | \token{long_slice}}
360 \production{short_slice}
361 {[\token{lower_bound}] ":" [\token{upper_bound}]}
362 \production{long_slice}
363 {\token{short_slice} ":" [\token{stride}]}
364 \production{lower_bound}
365 {\token{expression}}
366 \production{upper_bound}
367 {\token{expression}}
368 \production{stride}
369 {\token{expression}}
370 \production{ellipsis}
371 {"..."}
372\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000373
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000374There is ambiguity in the formal syntax here: anything that looks like
375an expression list also looks like a slice list, so any subscription
376can be interpreted as a slicing. Rather than further complicating the
377syntax, this is disambiguated by defining that in this case the
378interpretation as a subscription takes priority over the
379interpretation as a slicing (this is the case if the slice list
380contains no proper slice nor ellipses). Similarly, when the slice
381list has exactly one short slice and no trailing comma, the
382interpretation as a simple slicing takes priority over that as an
383extended slicing.\indexii{extended}{slicing}
384
385The semantics for a simple slicing are as follows. The primary must
386evaluate to a sequence object. The lower and upper bound expressions,
387if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000388\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000389sequence's length is added to it. The slicing now selects all items
390with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000391\code{\var{i} <= \var{k} < \var{j}} where \var{i}
392and \var{j} are the specified lower and upper bounds. This may be an
393empty sequence. It is not an error if \var{i} or \var{j} lie outside the
394range of valid indexes (such items don't exist so they aren't
395selected).
396
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000397The semantics for an extended slicing are as follows. The primary
398must evaluate to a mapping object, and it is indexed with a key that
399is constructed from the slice list, as follows. If the slice list
400contains at least one comma, the key is a tuple containing the
401conversion of the slice items; otherwise, the conversion of the lone
402slice item is the key. The conversion of a slice item that is an
403expression is that expression. The conversion of an ellipsis slice
404item is the built-in \code{Ellipsis} object. The conversion of a
405proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000406\member{start}, \member{stop} and \member{step} attributes are the
407values of the expressions given as lower bound, upper bound and
408stride, respectively, substituting \code{None} for missing
409expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000410\withsubitem{(slice object attribute)}{\ttindex{start}
411 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000412
Fred Drake2829f1c2001-06-23 05:27:20 +0000413
Fred Drake020f8c01998-07-28 19:32:59 +0000414\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000415\index{call}
416
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000417A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000418series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000419\obindex{callable}
420
Fred Drakecb4638a2001-07-06 22:49:53 +0000421\begin{productionlist}
422 \production{call}
423 {\token{primary} "(" [\token{argument_list} [","]] ")"}
424 \production{argument_list}
Fred Drake53815882002-03-15 23:21:37 +0000425 {\token{positional_arguments} ["," \token{keyword_arguments}}
426 \productioncont{ ["," "*" \token{expression} ["," "**" \token{expression}]]]}
427 \productioncont{| \token{keyword_arguments} ["," "*" \token{expression}}
428 \productioncont{ ["," "**" \token{expression}]]}
429 \productioncont{| "*" \token{expression} ["," "**" \token{expression}]}
430 \productioncont{| "**" \token{expression}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000431 \production{positional_arguments}
432 {\token{expression} ("," \token{expression})*}
433 \production{keyword_arguments}
434 {\token{keyword_item} ("," \token{keyword_item})*}
435 \production{keyword_item}
436 {\token{identifier} "=" \token{expression}}
437\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000438
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000439A trailing comma may be present after an argument list but does not
440affect the semantics.
441
Fred Drakef6669171998-05-06 19:52:49 +0000442The primary must evaluate to a callable object (user-defined
443functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000444objects, methods of class instances, and certain class instances
445themselves are callable; extensions may define additional callable
446object types). All argument expressions are evaluated before the call
447is attempted. Please refer to section \ref{function} for the syntax
448of formal parameter lists.
449
450If keyword arguments are present, they are first converted to
451positional arguments, as follows. First, a list of unfilled slots is
452created for the formal parameters. If there are N positional
453arguments, they are placed in the first N slots. Next, for each
454keyword argument, the identifier is used to determine the
455corresponding slot (if the identifier is the same as the first formal
456parameter name, the first slot is used, and so on). If the slot is
457already filled, a \exception{TypeError} exception is raised.
458Otherwise, the value of the argument is placed in the slot, filling it
459(even if the expression is \code{None}, it fills the slot). When all
460arguments have been processed, the slots that are still unfilled are
461filled with the corresponding default value from the function
462definition. (Default values are calculated, once, when the function
463is defined; thus, a mutable object such as a list or dictionary used
464as default value will be shared by all calls that don't specify an
465argument value for the corresponding slot; this should usually be
466avoided.) If there are any unfilled slots for which no default value
467is specified, a \exception{TypeError} exception is raised. Otherwise,
468the list of filled slots is used as the argument list for the call.
469
470If there are more positional arguments than there are formal parameter
471slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000472parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000473case, that formal parameter receives a tuple containing the excess
474positional arguments (or an empty tuple if there were no excess
475positional arguments).
476
477If any keyword argument does not correspond to a formal parameter
478name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000479parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000480case, that formal parameter receives a dictionary containing the
481excess keyword arguments (using the keywords as keys and the argument
482values as corresponding values), or a (new) empty dictionary if there
483were no excess keyword arguments.
484
Michael W. Hudson850d3982001-12-12 11:56:33 +0000485If the syntax \samp{*expression} appears in the function call,
486\samp{expression} must evaluate to a sequence. Elements from this
487sequence are treated as if they were additional positional arguments;
488if there are postional arguments \var{x1},...,\var{xN} , and
489\samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
490is equivalent to a call with M+N positional arguments
491\var{x1},...,\var{xN},\var{y1},...,\var{yM}.
492
493A consequence of this is that although the \samp{*expression} syntax
494appears \emph{after} any keyword arguments, it is processed
Fred Drakeb062cb22001-12-14 16:57:31 +0000495\emph{before} the keyword arguments (and the
496\samp{**expression} argument, if any -- see below). So:
Michael W. Hudson850d3982001-12-12 11:56:33 +0000497
498\begin{verbatim}
499>>> def f(a, b):
500... print a, b
501...
502>>> f(b=1, *(2,))
5032 1
504>>> f(a=1, *(2,))
505Traceback (most recent call last):
506 File "<stdin>", line 1, in ?
507TypeError: f() got multiple values for keyword argument 'a'
508>>> f(1, *(2,))
5091 2
510\end{verbatim}
511
Fred Drakeb062cb22001-12-14 16:57:31 +0000512It is unusual for both keyword arguments and the
513\samp{*expression} syntax to be used in the same call, so in practice
514this confusion does not arise.
Michael W. Hudson850d3982001-12-12 11:56:33 +0000515
516If the syntax \samp{**expression} appears in the function call,
517\samp{expression} must evaluate to a (subclass of) dictionary, the
518contents of which are treated as additional keyword arguments. In the
519case of a keyword appearing in both \samp{expression} and as an
520explicit keyword argument, a \exception{TypeError} exception is
521raised.
522
Fred Drakeea81edf1998-11-25 17:51:15 +0000523Formal parameters using the syntax \samp{*identifier} or
524\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000525as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000526\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000527outermost sublist corresponds to a single unnamed argument slot, and
528the argument value is assigned to the sublist using the usual tuple
529assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000530
Fred Drake5c07d9b1998-05-14 19:37:06 +0000531A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000532raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000533of the callable object.
534
535If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000536
537\begin{description}
538
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000539\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000540executed, passing it the argument list. The first thing the code
541block will do is bind the formal parameters to the arguments; this is
542described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000543\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000544function call.
545\indexii{function}{call}
546\indexiii{user-defined}{function}{call}
547\obindex{user-defined function}
548\obindex{function}
549
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000550\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000551interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
552Library Reference} for the descriptions of built-in functions and
553methods.
Fred Drakef6669171998-05-06 19:52:49 +0000554\indexii{function}{call}
555\indexii{built-in function}{call}
556\indexii{method}{call}
557\indexii{built-in method}{call}
558\obindex{built-in method}
559\obindex{built-in function}
560\obindex{method}
561\obindex{function}
562
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000563\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000564\obindex{class}
565\indexii{class object}{call}
566
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000567\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000568function is called, with an argument list that is one longer than the
569argument list of the call: the instance becomes the first argument.
570\obindex{class instance}
571\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000572\indexii{class instance}{call}
573
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000574\item[a class instance:] The class must define a \method{__call__()}
575method; the effect is then the same as if that method was called.
576\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000577\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000578
Fred Drakef6669171998-05-06 19:52:49 +0000579\end{description}
580
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000581
Fred Drake020f8c01998-07-28 19:32:59 +0000582\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000583
584The power operator binds more tightly than unary operators on its
585left; it binds less tightly than unary operators on its right. The
586syntax is:
587
Fred Drakecb4638a2001-07-06 22:49:53 +0000588\begin{productionlist}
589 \production{power}
590 {\token{primary} ["**" \token{u_expr}]}
591\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000592
593Thus, in an unparenthesized sequence of power and unary operators, the
594operators are evaluated from right to left (this does not constrain
595the evaluation order for the operands).
596
597The power operator has the same semantics as the built-in
598\function{pow()} function, when called with two arguments: it yields
599its left argument raised to the power of its right argument. The
600numeric arguments are first converted to a common type. The result
601type is that of the arguments after coercion; if the result is not
602expressible in that type (as in raising an integer to a negative
603power, or a negative floating point number to a broken power), a
604\exception{TypeError} exception is raised.
605
606
Fred Drakee15956b2000-04-03 04:51:13 +0000607\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000608\indexiii{unary}{arithmetic}{operation}
609\indexiii{unary}{bit-wise}{operation}
610
611All unary arithmetic (and bit-wise) operations have the same priority:
612
Fred Drakecb4638a2001-07-06 22:49:53 +0000613\begin{productionlist}
614 \production{u_expr}
615 {\token{power} | "-" \token{u_expr}
Fred Drakef6eafc32002-03-18 16:47:14 +0000616 | "+" \token{u_expr} | "{\~}" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000617\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000618
Fred Drake5c07d9b1998-05-14 19:37:06 +0000619The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000620numeric argument.
621\index{negation}
622\index{minus}
623
Fred Drake5c07d9b1998-05-14 19:37:06 +0000624The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000625unchanged.
626\index{plus}
627
Fred Drakee15956b2000-04-03 04:51:13 +0000628The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000629of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000630\code{x} is defined as \code{-(x+1)}. It only applies to integral
631numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000632\index{inversion}
633
634In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000635a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000636\exindex{TypeError}
637
Fred Drake2829f1c2001-06-23 05:27:20 +0000638
Fred Drake020f8c01998-07-28 19:32:59 +0000639\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000640\indexiii{binary}{arithmetic}{operation}
641
642The binary arithmetic operations have the conventional priority
643levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000644non-numeric types. Apart from the power operator, there are only two
645levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000646operators:
647
Fred Drakecb4638a2001-07-06 22:49:53 +0000648\begin{productionlist}
649 \production{m_expr}
650 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000651 | \token{m_expr} "//" \token{u_expr}
Fred Drake53815882002-03-15 23:21:37 +0000652 | \token{m_expr} "/" \token{u_expr}}
653 \productioncont{| \token{m_expr} "\%" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000654 \production{a_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000655 {\token{m_expr} | \token{a_expr} "+" \token{m_expr}
656 | \token{a_expr} "-" \token{m_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000657\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000658
Fred Drake5c07d9b1998-05-14 19:37:06 +0000659The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000660arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000661must be an integer (plain or long) and the other must be a sequence.
662In the former case, the numbers are converted to a common type and
663then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000664performed; a negative repetition factor yields an empty sequence.
665\index{multiplication}
666
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000667The \code{/} (division) and \code{//} (floor division) operators yield
668the quotient of their arguments. The numeric arguments are first
669converted to a common type. Plain or long integer division yields an
670integer of the same type; the result is that of mathematical division
671with the `floor' function applied to the result. Division by zero
672raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000673\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000674\exindex{ZeroDivisionError}
675\index{division}
676
Fred Drake5c07d9b1998-05-14 19:37:06 +0000677The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000678division of the first argument by the second. The numeric arguments
679are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000680the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000681point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000682\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
683yields a result with the same sign as its second operand (or zero);
684the absolute value of the result is strictly smaller than the second
685operand.
Fred Drakef6669171998-05-06 19:52:49 +0000686\index{modulo}
687
688The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000689following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
690modulo are also connected with the built-in function \function{divmod()}:
691\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000692floating point and complex numbers; there similar identities hold
693approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
694\code{floor(x/y) - 1} (for floats),\footnote{
695 If x is very close to an exact integer multiple of y, it's
696 possible for \code{floor(x/y)} to be one larger than
697 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
698 the latter result, in order to preserve that \code{divmod(x,y)[0]
699 * y + x \%{} y} be very close to \code{x}.
700} or \code{floor((x/y).real)} (for
701complex).
Fred Drakef6669171998-05-06 19:52:49 +0000702
Fred Drake5c07d9b1998-05-14 19:37:06 +0000703The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000704The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000705same type. In the former case, the numbers are converted to a common
706type and then added together. In the latter case, the sequences are
707concatenated.
708\index{addition}
709
Fred Drake5c07d9b1998-05-14 19:37:06 +0000710The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000711arguments. The numeric arguments are first converted to a common
712type.
713\index{subtraction}
714
Fred Drake2829f1c2001-06-23 05:27:20 +0000715
Fred Drake020f8c01998-07-28 19:32:59 +0000716\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000717\indexii{shifting}{operation}
718
719The shifting operations have lower priority than the arithmetic
720operations:
721
Fred Drakecb4638a2001-07-06 22:49:53 +0000722\begin{productionlist}
723 \production{shift_expr}
724 {\token{a_expr}
725 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
726\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000727
728These operators accept plain or long integers as arguments. The
729arguments are converted to a common type. They shift the first
730argument to the left or right by the number of bits given by the
731second argument.
732
733A right shift by \var{n} bits is defined as division by
734\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
735multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000736no overflow check so in that case the operation drops bits and flips
737the sign if the result is not less than \code{pow(2,31)} in absolute
738value. Negative shift counts raise a \exception{ValueError}
739exception.
Fred Drakef6669171998-05-06 19:52:49 +0000740\exindex{ValueError}
741
Fred Drake2829f1c2001-06-23 05:27:20 +0000742
Fred Drake020f8c01998-07-28 19:32:59 +0000743\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000744\indexiii{binary}{bit-wise}{operation}
745
746Each of the three bitwise operations has a different priority level:
747
Fred Drakecb4638a2001-07-06 22:49:53 +0000748\begin{productionlist}
749 \production{and_expr}
750 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
751 \production{xor_expr}
752 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
753 \production{or_expr}
754 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
755\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000756
Fred Drake5c07d9b1998-05-14 19:37:06 +0000757The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000758must be plain or long integers. The arguments are converted to a
759common type.
760\indexii{bit-wise}{and}
761
Fred Drake5c07d9b1998-05-14 19:37:06 +0000762The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000763arguments, which must be plain or long integers. The arguments are
764converted to a common type.
765\indexii{bit-wise}{xor}
766\indexii{exclusive}{or}
767
Fred Drake5c07d9b1998-05-14 19:37:06 +0000768The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000769arguments, which must be plain or long integers. The arguments are
770converted to a common type.
771\indexii{bit-wise}{or}
772\indexii{inclusive}{or}
773
Fred Drake2829f1c2001-06-23 05:27:20 +0000774
Fred Drake020f8c01998-07-28 19:32:59 +0000775\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000776\index{comparison}
777
Fred Drake1156f622000-09-19 18:10:05 +0000778Unlike C, all comparison operations in Python have the same priority,
779which is lower than that of any arithmetic, shifting or bitwise
780operation. Also unlike C, expressions like \code{a < b < c} have the
781interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000782\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000783
Fred Drakecb4638a2001-07-06 22:49:53 +0000784\begin{productionlist}
785 \production{comparison}
786 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
787 \production{comp_operator}
Fred Drake53815882002-03-15 23:21:37 +0000788 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="}
789 \productioncont{| "is" ["not"] | ["not"] "in"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000790\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000791
Fred Drake5c07d9b1998-05-14 19:37:06 +0000792Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000793
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000794Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000795equivalent to \code{x < y and y <= z}, except that \code{y} is
796evaluated only once (but in both cases \code{z} is not evaluated at all
797when \code{x < y} is found to be false).
798\indexii{chaining}{comparisons}
799
800Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
801expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
802operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000803to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000804\var{y opy z}, except that each expression is evaluated at most once.
805
806Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000807between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000808perfectly legal (though perhaps not pretty).
809
Fred Drake5c07d9b1998-05-14 19:37:06 +0000810The forms \code{<>} and \code{!=} are equivalent; for consistency with
811C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000812\code{<>} is also accepted. The \code{<>} spelling is considered
813obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000814
Fred Drake1156f622000-09-19 18:10:05 +0000815The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
816\code{!=} compare
817the values of two objects. The objects need not have the same type.
Fred Drakefd867712002-04-09 14:39:10 +0000818If both are numbers, they are converted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000819objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000820ordered consistently but arbitrarily.
821
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000822(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000823definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000824\keyword{not in} operators. In the future, the comparison rules for
825objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000826
827Comparison of objects of the same type depends on the type:
828
829\begin{itemize}
830
831\item
832Numbers are compared arithmetically.
833
834\item
835Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000836(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000837characters. Unicode and 8-bit strings are fully interoperable in this
838behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000839
840\item
841Tuples and lists are compared lexicographically using comparison of
842corresponding items.
843
844\item
Tim Peters20524db2001-10-01 20:22:45 +0000845Mappings (dictionaries) compare equal if and only if their sorted
846(key, value) lists compare equal.\footnote{The implementation computes
847 this efficiently, without constructing lists or sorting.}
848Outcomes other than equality are resolved consistently, but are not
Tim Peters1350c072001-10-01 20:25:26 +0000849otherwise defined.\footnote{Earlier versions of Python used
Tim Peters20524db2001-10-01 20:22:45 +0000850 lexicographic comparison of the sorted (key, value) lists, but this
851 was very expensive for the common case of comparing for equality. An
852 even earlier version of Python compared dictionaries by identity only,
853 but this caused surprises because people expected to be able to test
854 a dictionary for emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000855
856\item
857Most other types compare unequal unless they are the same object;
858the choice whether one object is considered smaller or larger than
859another one is made arbitrarily but consistently within one
860execution of a program.
861
862\end{itemize}
863
Fred Drake7399b9e2000-07-11 19:43:47 +0000864The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000865membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
866is a member of the set \var{s}, and false otherwise. \code{\var{x}
867not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
868The set membership test has traditionally been bound to sequences; an
869object is a member of a set if the set is a sequence and contains an
870element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000871to support membership tests without being a sequence. In particular,
872dictionaries support memership testing as a nicer way of spelling
873\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000874
Fred Drake34bafcc2001-01-14 02:57:14 +0000875For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000876only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000877\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000878
Fred Drake1156f622000-09-19 18:10:05 +0000879For the Unicode and string types, \code{\var{x} in \var{y}} is true if
880and only if there exists an index \var{i} such that \code{\var{x} ==
881\var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
882Unicode object of length \code{1}, a \exception{TypeError} exception
883is raised.
Fred Drake7399b9e2000-07-11 19:43:47 +0000884
885For user-defined classes which define the \method{__contains__()} method,
886\code{\var{x} in \var{y}} is true if and only if
887\code{\var{y}.__contains__(\var{x})} is true.
888
889For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000890do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
891and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000892\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
893do not raise \exception{IndexError} exception. (If any other exception
894is raised, it is as if \keyword{in} raised that exception).
895
896The operator \keyword{not in} is defined to have the inverse true value
897of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000898\opindex{in}
899\opindex{not in}
900\indexii{membership}{test}
901\obindex{sequence}
902
Fred Drake5c07d9b1998-05-14 19:37:06 +0000903The operators \keyword{is} and \keyword{is not} test for object identity:
904\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
905are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000906truth value.
907\opindex{is}
908\opindex{is not}
909\indexii{identity}{test}
910
Fred Drake2829f1c2001-06-23 05:27:20 +0000911
Fred Drake020f8c01998-07-28 19:32:59 +0000912\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000913\indexii{Boolean}{operation}
914
915Boolean operations have the lowest priority of all Python operations:
916
Fred Drakecb4638a2001-07-06 22:49:53 +0000917\begin{productionlist}
918 \production{expression}
919 {\token{or_test} | \token{lambda_form}}
920 \production{or_test}
921 {\token{and_test} | \token{or_test} "or" \token{and_test}}
922 \production{and_test}
923 {\token{not_test} | \token{and_test} "and" \token{not_test}}
924 \production{not_test}
925 {\token{comparison} | "not" \token{not_test}}
926 \production{lambda_form}
927 {"lambda" [\token{parameter_list}]: \token{expression}}
928\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000929
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000930In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000931used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000932as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000933(strings, tuples and lists), and empty mappings (dictionaries). All
934other values are interpreted as true.
935
Fred Drake5c07d9b1998-05-14 19:37:06 +0000936The operator \keyword{not} yields \code{1} if its argument is false,
937\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000938\opindex{not}
939
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000940The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000941\var{x} is false, its value is returned; otherwise, \var{y} is
942evaluated and the resulting value is returned.
943\opindex{and}
944
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000945The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000946\var{x} is true, its value is returned; otherwise, \var{y} is
947evaluated and the resulting value is returned.
948\opindex{or}
949
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000950(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000951and type they return to \code{0} and \code{1}, but rather return the
952last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000953This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000954replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000955\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000956invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000957same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000958not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000959
Jeremy Hylton2225add2002-04-01 21:05:21 +0000960\section{Lambdas\label{lambdas}}
961\indexii{lambda}{expression}
962\indexii{lambda}{form}
963\indexii{anonmymous}{function}
964
Fred Drakef6669171998-05-06 19:52:49 +0000965Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000966expressions. They are a shorthand to create anonymous functions; the
967expression \code{lambda \var{arguments}: \var{expression}}
Jeremy Hylton2225add2002-04-01 21:05:21 +0000968yields a function object. The unnamed object behaves like a function
969object define with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000970
971\begin{verbatim}
972def name(arguments):
973 return expression
974\end{verbatim}
975
976See section \ref{function} for the syntax of parameter lists. Note
977that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000978\label{lambda}
Fred Drake88382692001-06-05 02:17:02 +0000979
Fred Drake020f8c01998-07-28 19:32:59 +0000980\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000981\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +0000982
Fred Drakecb4638a2001-07-06 22:49:53 +0000983\begin{productionlist}
984 \production{expression_list}
985 {\token{expression} ( "," \token{expression} )* [","]}
986\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000987
Fred Drakec009d192000-04-25 21:09:10 +0000988An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000989tuple. The length of the tuple is the number of expressions in the
990list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +0000991\obindex{tuple}
992
993The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000994\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +0000995expression without a trailing comma doesn't create a
996tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +0000997(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000998\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000999\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +00001000
Fred Draked09120b1999-04-29 16:43:42 +00001001
Fred Drake020f8c01998-07-28 19:32:59 +00001002\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +00001003
Fred Draked09120b1999-04-29 16:43:42 +00001004The following table summarizes the operator
1005precedences\indexii{operator}{precedence} in Python, from lowest
1006precedence (least binding) to highest precedence (most binding).
1007Operators in the same box have the same precedence. Unless the syntax
1008is explicitly given, operators are binary. Operators in the same box
1009group left to right (except for comparisons, which chain from left to
Fred Drake2a222002000-12-11 22:39:24 +00001010right --- see above, and exponentiation, which groups from right to
1011left).
Fred Drakef6669171998-05-06 19:52:49 +00001012
Fred Draked09120b1999-04-29 16:43:42 +00001013\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001014 \lineii{\keyword{lambda}} {Lambda expression}
1015 \hline
1016 \lineii{\keyword{or}} {Boolean OR}
1017 \hline
1018 \lineii{\keyword{and}} {Boolean AND}
1019 \hline
1020 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1021 \hline
1022 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1023 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1024 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +00001025 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001026 {Comparisons}
1027 \hline
1028 \lineii{\code{|}} {Bitwise OR}
1029 \hline
1030 \lineii{\code{\^}} {Bitwise XOR}
1031 \hline
1032 \lineii{\code{\&}} {Bitwise AND}
1033 \hline
Fred Drake24e7a292001-04-12 12:37:03 +00001034 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001035 \hline
1036 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1037 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001038 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001039 {Multiplication, division, remainder}
1040 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001041 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1042 \lineii{\code{\~\var{x}}} {Bitwise not}
1043 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001044 \lineii{\code{**}} {Exponentiation}
1045 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001046 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1047 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1048 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1049 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001050 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001051 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1052 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1053 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1054 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1055\end{tableii}