blob: 34dfeb1de43da818bd9e1f2f72d1e88062eab3ef [file] [log] [blame]
Guido van Rossum46f3e001992-08-14 09:11:01 +00001\chapter{Expressions and conditions}
2\index{expression}
3\index{condition}
4
5{\bf Note:} In this and the following chapters, extended BNF notation
6will be used to describe syntax, not lexical analysis.
7\index{BNF}
8
9This chapter explains the meaning of the elements of expressions and
10conditions. Conditions are a superset of expressions, and a condition
11may be used wherever an expression is required by enclosing it in
12parentheses. The only places where expressions are used in the syntax
13instead of conditions is in expression statements and on the
14right-hand side of assignment statements; this catches some nasty bugs
15like accidentally writing \verb\x == 1\ instead of \verb\x = 1\.
16\indexii{assignment}{statement}
17
18The comma plays several roles in Python's syntax. It is usually an
19operator with a lower precedence than all others, but occasionally
20serves other purposes as well; e.g. it separates function arguments,
21is used in list and dictionary constructors, and has special semantics
22in \verb\print\ statements.
23\index{comma}
24
25When (one alternative of) a syntax rule has the form
26
27\begin{verbatim}
28name: othername
29\end{verbatim}
30
31and no semantics are given, the semantics of this form of \verb\name\
32are the same as for \verb\othername\.
33\index{syntax}
34
35\section{Arithmetic conversions}
36\indexii{arithmetic}{conversion}
37
38When a description of an arithmetic operator below uses the phrase
39``the numeric arguments are converted to a common type'',
40this both means that if either argument is not a number, a
41\verb\TypeError\ exception is raised, and that otherwise
42the following conversions are applied:
43\exindex{TypeError}
44\indexii{floating point}{number}
45\indexii{long}{integer}
46\indexii{plain}{integer}
47
48\begin{itemize}
49\item first, if either argument is a floating point number,
50 the other is converted to floating point;
51\item else, if either argument is a long integer,
52 the other is converted to long integer;
53\item otherwise, both must be plain integers and no conversion
54 is necessary.
55\end{itemize}
56
57\section{Atoms}
58\index{atom}
59
60Atoms are the most basic elements of expressions. Forms enclosed in
61reverse quotes or in parentheses, brackets or braces are also
62categorized syntactically as atoms. The syntax for atoms is:
63
64\begin{verbatim}
65atom: identifier | literal | enclosure
66enclosure: parenth_form | list_display | dict_display | string_conversion
67\end{verbatim}
68
69\subsection{Identifiers (Names)}
70\index{name}
71\index{identifier}
72
73An identifier occurring as an atom is a reference to a local, global
74or built-in name binding. If a name can be assigned to anywhere in a
75code block, and is not mentioned in a \verb\global\ statement in that
76code block, it refers to a local name throughout that code block.
77Otherwise, it refers to a global name if one exists, else to a
78built-in name.
79\indexii{name}{binding}
80\index{code block}
81\stindex{global}
82\indexii{built-in}{name}
83\indexii{global}{name}
84
85When the name is bound to an object, evaluation of the atom yields
86that object. When a name is not bound, an attempt to evaluate it
87raises a \verb\NameError\ exception.
88\exindex{NameError}
89
90\subsection{Literals}
91\index{literal}
92
93Python knows string and numeric literals:
94
95\begin{verbatim}
96literal: stringliteral | integer | longinteger | floatnumber
97\end{verbatim}
98
99Evaluation of a literal yields an object of the given type (string,
100integer, long integer, floating point number) with the given value.
101The value may be approximated in the case of floating point literals.
102See section \ref{literals} for details.
103
104All literals correspond to immutable data types, and hence the
105object's identity is less important than its value. Multiple
106evaluations of literals with the same value (either the same
107occurrence in the program text or a different occurrence) may obtain
108the same object or a different object with the same value.
109\indexiii{immutable}{data}{type}
110
111(In the original implementation, all literals in the same code block
112with the same type and value yield the same object.)
113
114\subsection{Parenthesized forms}
115\index{parenthesized form}
116
117A parenthesized form is an optional condition list enclosed in
118parentheses:
119
120\begin{verbatim}
121parenth_form: "(" [condition_list] ")"
122\end{verbatim}
123
124A parenthesized condition list yields whatever that condition list
125yields.
126
127An empty pair of parentheses yields an empty tuple object. Since
128tuples are immutable, the rules for literals apply here.
129\indexii{empty}{tuple}
130
131(Note that tuples are not formed by the parentheses, but rather by use
132of the comma operator. The exception is the empty tuple, for which
133parentheses {\em are} required --- allowing unparenthesized ``nothing''
134in expressions would causes ambiguities and allow common typos to
135pass uncaught.)
136\index{comma}
137\indexii{tuple}{display}
138
139\subsection{List displays}
140\indexii{list}{display}
141
142A list display is a possibly empty series of conditions enclosed in
143square brackets:
144
145\begin{verbatim}
146list_display: "[" [condition_list] "]"
147\end{verbatim}
148
149A list display yields a new list object.
150\obindex{list}
151
152If it has no condition list, the list object has no items. Otherwise,
153the elements of the condition list are evaluated from left to right
154and inserted in the list object in that order.
155\indexii{empty}{list}
156
157\subsection{Dictionary displays} \label{dict}
158\indexii{dictionary}{display}
159
160A dictionary display is a possibly empty series of key/datum pairs
161enclosed in curly braces:
162\index{key}
163\index{datum}
164\index{key/datum pair}
165
166\begin{verbatim}
167dict_display: "{" [key_datum_list] "}"
168key_datum_list: key_datum ("," key_datum)* [","]
169key_datum: condition ":" condition
170\end{verbatim}
171
172A dictionary display yields a new dictionary object.
173\obindex{dictionary}
174
175The key/datum pairs are evaluated from left to right to define the
176entries of the dictionary: each key object is used as a key into the
177dictionary to store the corresponding datum.
178
179Keys must be strings, otherwise a \verb\TypeError\ exception is
180raised. Clashes between duplicate keys are not detected; the last
181datum (textually rightmost in the display) stored for a given key
182value prevails.
183\exindex{TypeError}
184
185\subsection{String conversions}
186\indexii{string}{conversion}
187
188A string conversion is a condition list enclosed in reverse (or
189backward) quotes:
190
191\begin{verbatim}
192string_conversion: "`" condition_list "`"
193\end{verbatim}
194
195A string conversion evaluates the contained condition list and
196converts the resulting object into a string according to rules
197specific to its type.
198
199If the object is a string, a number, \verb\None\, or a tuple, list or
200dictionary containing only objects whose type is one of these, the
201resulting string is a valid Python expression which can be passed to
202the built-in function \verb\eval()\ to yield an expression with the
203same value (or an approximation, if floating point numbers are
204involved).
205
206(In particular, converting a string adds quotes around it and converts
207``funny'' characters to escape sequences that are safe to print.)
208
209It is illegal to attempt to convert recursive objects (e.g. lists or
210dictionaries that contain a reference to themselves, directly or
211indirectly.)
212\obindex{recursive}
213
214\section{Primaries} \label{primaries}
215\index{primary}
216
217Primaries represent the most tightly bound operations of the language.
218Their syntax is:
219
220\begin{verbatim}
221primary: atom | attributeref | subscription | slicing | call
222\end{verbatim}
223
224\subsection{Attribute references}
225\indexii{attribute}{reference}
226
227An attribute reference is a primary followed by a period and a name:
228
229\begin{verbatim}
230attributeref: primary "." identifier
231\end{verbatim}
232
233The primary must evaluate to an object of a type that supports
234attribute references, e.g. a module or a list. This object is then
235asked to produce the attribute whose name is the identifier. If this
236attribute is not available, the exception \verb\AttributeError\ is
237raised. Otherwise, the type and value of the object produced is
238determined by the object. Multiple evaluations of the same attribute
239reference may yield different objects.
240\obindex{module}
241\obindex{list}
242
243\subsection{Subscriptions}
244\index{subscription}
245
246A subscription selects an item of a sequence (string, tuple or list)
247or mapping (dictionary) object:
248\obindex{sequence}
249\obindex{mapping}
250\obindex{string}
251\obindex{tuple}
252\obindex{list}
253\obindex{dictionary}
254\indexii{sequence}{item}
255
256\begin{verbatim}
257subscription: primary "[" condition "]"
258\end{verbatim}
259
260The primary must evaluate to an object of a sequence or mapping type.
261
262If it is a mapping, the condition must evaluate to an object whose
263value is one of the keys of the mapping, and the subscription selects
264the value in the mapping that corresponds to that key.
265
266If it is a sequence, the condition must evaluate to a plain integer.
267If this value is negative, the length of the sequence is added to it
268(so that, e.g. \verb\x[-1]\ selects the last item of \verb\x\.)
269The resulting value must be a nonnegative integer smaller than the
270number of items in the sequence, and the subscription selects the item
271whose index is that value (counting from zero).
272
273A string's items are characters. A character is not a separate data
274type but a string of exactly one character.
275\index{character}
276\indexii{string}{item}
277
278\subsection{Slicings}
279\index{slicing}
280\index{slice}
281
282A slicing (or slice) selects a range of items in a sequence (string,
283tuple or list) object:
284\obindex{sequence}
285\obindex{string}
286\obindex{tuple}
287\obindex{list}
288
289\begin{verbatim}
290slicing: primary "[" [condition] ":" [condition] "]"
291\end{verbatim}
292
293The primary must evaluate to a sequence object. The lower and upper
294bound expressions, if present, must evaluate to plain integers;
295defaults are zero and the sequence's length, respectively. If either
296bound is negative, the sequence's length is added to it. The slicing
297now selects all items with index $k$ such that $i <= k < j$ where $i$
298and $j$ are the specified lower and upper bounds. This may be an
299empty sequence. It is not an error if $i$ or $j$ lie outside the
300range of valid indexes (such items don't exist so they aren't
301selected).
302
303\subsection{Calls} \label{calls}
304\index{call}
305
306A call calls a callable object (e.g. a function) with a possibly empty
307series of arguments:
308\obindex{callable}
309
310\begin{verbatim}
311call: primary "(" [condition_list] ")"
312\end{verbatim}
313
314The primary must evaluate to a callable object (user-defined
315functions, built-in functions, methods of built-in objects, class
316objects, and methods of class instances are callable). If it is a
317class, the argument list must be empty; otherwise, the arguments are
318evaluated.
319
320A call always returns some value, possibly \verb\None\, unless it
321raises an exception. How this value is computed depends on the type
322of the callable object. If it is:
323
324\begin{description}
325
326\item[a user-defined function:] the code block for the function is
327executed, passing it the argument list. The first thing the code
328block will do is bind the formal parameters to the arguments; this is
329described in section \ref{function}. When the code block executes a
330\verb\return\ statement, this specifies the return value of the
331function call.
332\indexii{function}{call}
333\indexiii{user-defined}{function}{call}
334\obindex{user-defined function}
335\obindex{function}
336
337\item[a built-in function or method:] the result is up to the
338interpreter; see the library reference manual for the descriptions of
339built-in functions and methods.
340\indexii{function}{call}
341\indexii{built-in function}{call}
342\indexii{method}{call}
343\indexii{built-in method}{call}
344\obindex{built-in method}
345\obindex{built-in function}
346\obindex{method}
347\obindex{function}
348
349\item[a class object:] a new instance of that class is returned.
350\obindex{class}
351\indexii{class object}{call}
352
353\item[a class instance method:] the corresponding user-defined
354function is called, with an argument list that is one longer than the
355argument list of the call: the instance becomes the first argument.
356\obindex{class instance}
357\obindex{instance}
358\indexii{instance}{call}
359\indexii{class instance}{call}
360
361\end{description}
362
363\section{Unary arithmetic operations}
364\indexiii{unary}{arithmetic}{operation}
365\indexiii{unary}{bit-wise}{operation}
366
367All unary arithmetic (and bit-wise) operations have the same priority:
368
369\begin{verbatim}
370u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr
371\end{verbatim}
372
373The unary \verb\"-"\ (minus) operator yields the negation of its
374numeric argument.
375\index{negation}
376\index{minus}
377
378The unary \verb\"+"\ (plus) operator yields its numeric argument
379unchanged.
380\index{plus}
381
382The unary \verb\"~"\ (invert) operator yields the bit-wise inversion
383of its plain or long integer argument. The bit-wise inversion of
384\verb\x\ is defined as \verb\-(x+1)\.
385\index{inversion}
386
387In all three cases, if the argument does not have the proper type,
388a \verb\TypeError\ exception is raised.
389\exindex{TypeError}
390
391\section{Binary arithmetic operations}
392\indexiii{binary}{arithmetic}{operation}
393
394The binary arithmetic operations have the conventional priority
395levels. Note that some of these operations also apply to certain
396non-numeric types. There is no ``power'' operator, so there are only
397two levels, one for multiplicative operators and one for additive
398operators:
399
400\begin{verbatim}
401m_expr: u_expr | m_expr "*" u_expr
402 | m_expr "/" u_expr | m_expr "%" u_expr
403a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
404\end{verbatim}
405
406The \verb\"*"\ (multiplication) operator yields the product of its
407arguments. The arguments must either both be numbers, or one argument
408must be a plain integer and the other must be a sequence. In the
409former case, the numbers are converted to a common type and then
410multiplied together. In the latter case, sequence repetition is
411performed; a negative repetition factor yields an empty sequence.
412\index{multiplication}
413
414The \verb\"/"\ (division) operator yields the quotient of its
415arguments. The numeric arguments are first converted to a common
416type. Plain or long integer division yields an integer of the same
417type; the result is that of mathematical division with the `floor'
418function applied to the result. Division by zero raises the
419\verb\ZeroDivisionError\ exception.
420\exindex{ZeroDivisionError}
421\index{division}
422
423The \verb\"%"\ (modulo) operator yields the remainder from the
424division of the first argument by the second. The numeric arguments
425are first converted to a common type. A zero right argument raises
426the \verb\ZeroDivisionError\ exception. The arguments may be floating
427point numbers, e.g. \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo
428operator always yields a result with the same sign as its second
429operand (or zero); the absolute value of the result is strictly
430smaller than the second operand.
431\index{modulo}
432
433The integer division and modulo operators are connected by the
434following identity: \verb\x == (x/y)*y + (x%y)\. Integer division and
435modulo are also connected with the built-in function \verb\divmod()\:
436\verb\divmod(x, y) == (x/y, x%y)\. These identities don't hold for
437floating point numbers; there a similar identity holds where
438\verb\x/y\ is replaced by \verb\floor(x/y)\).
439
440The \verb\"+"\ (addition) operator yields the sum of its arguments.
441The arguments must either both be numbers, or both sequences of the
442same type. In the former case, the numbers are converted to a common
443type and then added together. In the latter case, the sequences are
444concatenated.
445\index{addition}
446
447The \verb\"-"\ (subtraction) operator yields the difference of its
448arguments. The numeric arguments are first converted to a common
449type.
450\index{subtraction}
451
452\section{Shifting operations}
453\indexii{shifting}{operation}
454
455The shifting operations have lower priority than the arithmetic
456operations:
457
458\begin{verbatim}
459shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
460\end{verbatim}
461
462These operators accept plain or long integers as arguments. The
463arguments are converted to a common type. They shift the first
464argument to the left or right by the number of bits given by the
465second argument.
466
467A right shift by $n$ bits is defined as division by $2^n$. A left
468shift by $n$ bits is defined as multiplication with $2^n$; for plain
469integers there is no overflow check so this drops bits and flip the
470sign if the result is not less than $2^{31}$ in absolute value.
471
472Negative shift counts raise a \verb\ValueError\ exception.
473\exindex{ValueError}
474
475\section{Binary bit-wise operations}
476\indexiii{binary}{bit-wise}{operation}
477
478Each of the three bitwise operations has a different priority level:
479
480\begin{verbatim}
481and_expr: shift_expr | and_expr "&" shift_expr
482xor_expr: and_expr | xor_expr "^" and_expr
483or_expr: xor_expr | or_expr "|" xor_expr
484\end{verbatim}
485
486The \verb\"&"\ operator yields the bitwise AND of its arguments, which
487must be plain or long integers. The arguments are converted to a
488common type.
489\indexii{bit-wise}{and}
490
491The \verb\"^"\ operator yields the bitwise XOR (exclusive OR) of its
492arguments, which must be plain or long integers. The arguments are
493converted to a common type.
494\indexii{bit-wise}{xor}
495\indexii{exclusive}{or}
496
497The \verb\"|"\ operator yields the bitwise (inclusive) OR of its
498arguments, which must be plain or long integers. The arguments are
499converted to a common type.
500\indexii{bit-wise}{or}
501\indexii{inclusive}{or}
502
503\section{Comparisons}
504\index{comparison}
505
506Contrary to C, all comparison operations in Python have the same
507priority, which is lower than that of any arithmetic, shifting or
508bitwise operation. Also contrary to C, expressions like
509\verb\a < b < c\ have the interpretation that is conventional in
510mathematics:
511\index{C}
512
513\begin{verbatim}
514comparison: or_expr (comp_operator or_expr)*
515comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
516\end{verbatim}
517
518Comparisons yield integer values: 1 for true, 0 for false.
519
520Comparisons can be chained arbitrarily, e.g. $x < y <= z$ is
521equivalent to $x < y$ \verb\and\ $y <= z$, except that $y$ is
522evaluated only once (but in both cases $z$ is not evaluated at all
523when $x < y$ is found to be false).
524\indexii{chaining}{comparisons}
525
526Formally, $e_0 op_1 e_1 op_2 e_2 ...e_{n-1} op_n e_n$ is equivalent to
527$e_0 op_1 e_1$ \verb\and\ $e_1 op_2 e_2$ \verb\and\ ... \verb\and\
528$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
529
530Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
531between $e_0$ and $e_2$, e.g. $x < y > z$ is perfectly legal.
532
533The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with
534C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below
535\verb\<>\ is also implied.
536
537The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
538the values of two objects. The objects needn't have the same type.
539If both are numbers, they are coverted to a common type. Otherwise,
540objects of different types {\em always} compare unequal, and are
541ordered consistently but arbitrarily.
542
543(This unusual definition of comparison is done to simplify the
544definition of operations like sorting and the \verb\in\ and \verb\not
545in\ operators.)
546
547Comparison of objects of the same type depends on the type:
548
549\begin{itemize}
550
551\item
552Numbers are compared arithmetically.
553
554\item
555Strings are compared lexicographically using the numeric equivalents
556(the result of the built-in function \verb\ord\) of their characters.
557
558\item
559Tuples and lists are compared lexicographically using comparison of
560corresponding items.
561
562\item
563Mappings (dictionaries) are compared through lexicographic
564comparison of their sorted (key, value) lists.%
565\footnote{This is expensive since it requires sorting the keys first,
566but about the only sensible definition. It was tried to compare
567dictionaries by identity only, but this caused surprises because
568people expected to be able to test a dictionary for emptiness by
569comparing it to {\tt \{\}}.}
570
571\item
572Most other types compare unequal unless they are the same object;
573the choice whether one object is considered smaller or larger than
574another one is made arbitrarily but consistently within one
575execution of a program.
576
577\end{itemize}
578
579The operators \verb\in\ and \verb\not in\ test for sequence
580membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and
581only if there exists an index $i$ such that $x = y[i]$.
582$x ~\verb\not in\~ y$ yields the inverse truth value. The exception
583\verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is
584a string and $x$ is not a string of length one.%
585\footnote{The latter restriction is sometimes a nuisance.}
586\opindex{in}
587\opindex{not in}
588\indexii{membership}{test}
589\obindex{sequence}
590
591The operators \verb\is\ and \verb\is not\ test for object identity:
592$x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same
593object. $x ~\verb\is not\~ y$ yields the inverse truth value.
594\opindex{is}
595\opindex{is not}
596\indexii{identity}{test}
597
598\section{Boolean operations} \label{Booleans}
599\indexii{Boolean}{operation}
600
601Boolean operations have the lowest priority of all Python operations:
602
603\begin{verbatim}
604condition: or_test
605or_test: and_test | or_test "or" and_test
606and_test: not_test | and_test "and" not_test
607not_test: comparison | "not" not_test
608\end{verbatim}
609
610In the context of Boolean operations, and also when conditions are
611used by control flow statements, the following values are interpreted
612as false: \verb\None\, numeric zero of all types, empty sequences
613(strings, tuples and lists), and empty mappings (dictionaries). All
614other values are interpreted as true.
615
616The operator \verb\not\ yields 1 if its argument is false, 0 otherwise.
617\opindex{not}
618
619The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false,
620its value is returned; otherwise, $y$ is evaluated and the resulting
621value is returned.
622\opindex{and}
623
624The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true,
625its value is returned; otherwise, $y$ is evaluated and the resulting
626value is returned.
627\opindex{or}
628
629(Note that \verb\and\ and \verb\or\ do not restrict the value and type
630they return to 0 and 1, but rather return the last evaluated argument.
631This is sometimes useful, e.g. if \verb\s\ is a string that should be
632replaced by a default value if it is empty, the expression
633\verb\s or 'foo'\ yields the desired value. Because \verb\not\ has to
634invent a value anyway, it does not bother to return a value of the
635same type as its argument, so e.g. \verb\not 'foo'\ yields \verb\0\,
636not \verb\''\.)
637
638\section{Expression lists and condition lists}
639\indexii{expression}{list}
640\indexii{condition}{list}
641
642\begin{verbatim}
643expr_list: or_expr ("," or_expr)* [","]
644cond_list: condition ("," condition)* [","]
645\end{verbatim}
646
647The only difference between expression lists and condition lists is
648the lowest priority of operators that can be used in them without
649being enclosed in parentheses; condition lists allow all operators,
650while expression lists don't allow comparisons and Boolean operators
651(they do allow bitwise and shift operators though).
652
653Expression lists are used in expression statements and assignments;
654condition lists are used everywhere else where a list of
655comma-separated values is required.
656
657An expression (condition) list containing at least one comma yields a
658tuple. The length of the tuple is the number of expressions
659(conditions) in the list. The expressions (conditions) are evaluated
660from left to right. (Conditions lists are used syntactically is a few
661places where no tuple is constructed but a list of values is needed
662nevertheless.)
663\obindex{tuple}
664
665The trailing comma is required only to create a single tuple (a.k.a. a
666{\em singleton}); it is optional in all other cases. A single
667expression (condition) without a trailing comma doesn't create a
668tuple, but rather yields the value of that expression (condition).
669\indexii{trailing}{comma}
670
671(To create an empty tuple, use an empty pair of parentheses:
672\verb\()\.)