blob: 59ba90a4d8e08036f232b3ea4c6b9d0d8cf90f69 [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
Guido van Rossumb2c65561993-05-12 08:53:36 +0000179Restrictions on the types of the key values are listed earlier in
180section \ref{types}.
181Clashes between duplicate keys are not detected; the last
Guido van Rossum46f3e001992-08-14 09:11:01 +0000182datum (textually rightmost in the display) stored for a given key
183value prevails.
184\exindex{TypeError}
185
186\subsection{String conversions}
187\indexii{string}{conversion}
188
189A string conversion is a condition list enclosed in reverse (or
190backward) quotes:
191
192\begin{verbatim}
193string_conversion: "`" condition_list "`"
194\end{verbatim}
195
196A string conversion evaluates the contained condition list and
197converts the resulting object into a string according to rules
198specific to its type.
199
200If the object is a string, a number, \verb\None\, or a tuple, list or
201dictionary containing only objects whose type is one of these, the
202resulting string is a valid Python expression which can be passed to
203the built-in function \verb\eval()\ to yield an expression with the
204same value (or an approximation, if floating point numbers are
205involved).
206
207(In particular, converting a string adds quotes around it and converts
208``funny'' characters to escape sequences that are safe to print.)
209
210It is illegal to attempt to convert recursive objects (e.g. lists or
211dictionaries that contain a reference to themselves, directly or
212indirectly.)
213\obindex{recursive}
214
215\section{Primaries} \label{primaries}
216\index{primary}
217
218Primaries represent the most tightly bound operations of the language.
219Their syntax is:
220
221\begin{verbatim}
222primary: atom | attributeref | subscription | slicing | call
223\end{verbatim}
224
225\subsection{Attribute references}
226\indexii{attribute}{reference}
227
228An attribute reference is a primary followed by a period and a name:
229
230\begin{verbatim}
231attributeref: primary "." identifier
232\end{verbatim}
233
234The primary must evaluate to an object of a type that supports
235attribute references, e.g. a module or a list. This object is then
236asked to produce the attribute whose name is the identifier. If this
237attribute is not available, the exception \verb\AttributeError\ is
238raised. Otherwise, the type and value of the object produced is
239determined by the object. Multiple evaluations of the same attribute
240reference may yield different objects.
241\obindex{module}
242\obindex{list}
243
244\subsection{Subscriptions}
245\index{subscription}
246
247A subscription selects an item of a sequence (string, tuple or list)
248or mapping (dictionary) object:
249\obindex{sequence}
250\obindex{mapping}
251\obindex{string}
252\obindex{tuple}
253\obindex{list}
254\obindex{dictionary}
255\indexii{sequence}{item}
256
257\begin{verbatim}
258subscription: primary "[" condition "]"
259\end{verbatim}
260
261The primary must evaluate to an object of a sequence or mapping type.
262
263If it is a mapping, the condition must evaluate to an object whose
264value is one of the keys of the mapping, and the subscription selects
265the value in the mapping that corresponds to that key.
266
267If it is a sequence, the condition must evaluate to a plain integer.
268If this value is negative, the length of the sequence is added to it
269(so that, e.g. \verb\x[-1]\ selects the last item of \verb\x\.)
270The resulting value must be a nonnegative integer smaller than the
271number of items in the sequence, and the subscription selects the item
272whose index is that value (counting from zero).
273
274A string's items are characters. A character is not a separate data
275type but a string of exactly one character.
276\index{character}
277\indexii{string}{item}
278
279\subsection{Slicings}
280\index{slicing}
281\index{slice}
282
283A slicing (or slice) selects a range of items in a sequence (string,
284tuple or list) object:
285\obindex{sequence}
286\obindex{string}
287\obindex{tuple}
288\obindex{list}
289
290\begin{verbatim}
291slicing: primary "[" [condition] ":" [condition] "]"
292\end{verbatim}
293
294The primary must evaluate to a sequence object. The lower and upper
295bound expressions, if present, must evaluate to plain integers;
296defaults are zero and the sequence's length, respectively. If either
297bound is negative, the sequence's length is added to it. The slicing
298now selects all items with index $k$ such that $i <= k < j$ where $i$
299and $j$ are the specified lower and upper bounds. This may be an
300empty sequence. It is not an error if $i$ or $j$ lie outside the
301range of valid indexes (such items don't exist so they aren't
302selected).
303
304\subsection{Calls} \label{calls}
305\index{call}
306
307A call calls a callable object (e.g. a function) with a possibly empty
308series of arguments:
309\obindex{callable}
310
311\begin{verbatim}
312call: primary "(" [condition_list] ")"
313\end{verbatim}
314
315The primary must evaluate to a callable object (user-defined
316functions, built-in functions, methods of built-in objects, class
317objects, and methods of class instances are callable). If it is a
318class, the argument list must be empty; otherwise, the arguments are
319evaluated.
320
321A call always returns some value, possibly \verb\None\, unless it
322raises an exception. How this value is computed depends on the type
323of the callable object. If it is:
324
325\begin{description}
326
327\item[a user-defined function:] the code block for the function is
328executed, passing it the argument list. The first thing the code
329block will do is bind the formal parameters to the arguments; this is
330described in section \ref{function}. When the code block executes a
331\verb\return\ statement, this specifies the return value of the
332function call.
333\indexii{function}{call}
334\indexiii{user-defined}{function}{call}
335\obindex{user-defined function}
336\obindex{function}
337
338\item[a built-in function or method:] the result is up to the
339interpreter; see the library reference manual for the descriptions of
340built-in functions and methods.
341\indexii{function}{call}
342\indexii{built-in function}{call}
343\indexii{method}{call}
344\indexii{built-in method}{call}
345\obindex{built-in method}
346\obindex{built-in function}
347\obindex{method}
348\obindex{function}
349
350\item[a class object:] a new instance of that class is returned.
351\obindex{class}
352\indexii{class object}{call}
353
354\item[a class instance method:] the corresponding user-defined
355function is called, with an argument list that is one longer than the
356argument list of the call: the instance becomes the first argument.
357\obindex{class instance}
358\obindex{instance}
359\indexii{instance}{call}
360\indexii{class instance}{call}
361
362\end{description}
363
364\section{Unary arithmetic operations}
365\indexiii{unary}{arithmetic}{operation}
366\indexiii{unary}{bit-wise}{operation}
367
368All unary arithmetic (and bit-wise) operations have the same priority:
369
370\begin{verbatim}
371u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr
372\end{verbatim}
373
374The unary \verb\"-"\ (minus) operator yields the negation of its
375numeric argument.
376\index{negation}
377\index{minus}
378
379The unary \verb\"+"\ (plus) operator yields its numeric argument
380unchanged.
381\index{plus}
382
383The unary \verb\"~"\ (invert) operator yields the bit-wise inversion
384of its plain or long integer argument. The bit-wise inversion of
385\verb\x\ is defined as \verb\-(x+1)\.
386\index{inversion}
387
388In all three cases, if the argument does not have the proper type,
389a \verb\TypeError\ exception is raised.
390\exindex{TypeError}
391
392\section{Binary arithmetic operations}
393\indexiii{binary}{arithmetic}{operation}
394
395The binary arithmetic operations have the conventional priority
396levels. Note that some of these operations also apply to certain
397non-numeric types. There is no ``power'' operator, so there are only
398two levels, one for multiplicative operators and one for additive
399operators:
400
401\begin{verbatim}
402m_expr: u_expr | m_expr "*" u_expr
403 | m_expr "/" u_expr | m_expr "%" u_expr
404a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
405\end{verbatim}
406
407The \verb\"*"\ (multiplication) operator yields the product of its
408arguments. The arguments must either both be numbers, or one argument
409must be a plain integer and the other must be a sequence. In the
410former case, the numbers are converted to a common type and then
411multiplied together. In the latter case, sequence repetition is
412performed; a negative repetition factor yields an empty sequence.
413\index{multiplication}
414
415The \verb\"/"\ (division) operator yields the quotient of its
416arguments. The numeric arguments are first converted to a common
417type. Plain or long integer division yields an integer of the same
418type; the result is that of mathematical division with the `floor'
419function applied to the result. Division by zero raises the
420\verb\ZeroDivisionError\ exception.
421\exindex{ZeroDivisionError}
422\index{division}
423
424The \verb\"%"\ (modulo) operator yields the remainder from the
425division of the first argument by the second. The numeric arguments
426are first converted to a common type. A zero right argument raises
427the \verb\ZeroDivisionError\ exception. The arguments may be floating
428point numbers, e.g. \verb\3.14 % 0.7\ equals \verb\0.34\. The modulo
429operator always yields a result with the same sign as its second
430operand (or zero); the absolute value of the result is strictly
431smaller than the second operand.
432\index{modulo}
433
434The integer division and modulo operators are connected by the
435following identity: \verb\x == (x/y)*y + (x%y)\. Integer division and
436modulo are also connected with the built-in function \verb\divmod()\:
437\verb\divmod(x, y) == (x/y, x%y)\. These identities don't hold for
438floating point numbers; there a similar identity holds where
439\verb\x/y\ is replaced by \verb\floor(x/y)\).
440
441The \verb\"+"\ (addition) operator yields the sum of its arguments.
442The arguments must either both be numbers, or both sequences of the
443same type. In the former case, the numbers are converted to a common
444type and then added together. In the latter case, the sequences are
445concatenated.
446\index{addition}
447
448The \verb\"-"\ (subtraction) operator yields the difference of its
449arguments. The numeric arguments are first converted to a common
450type.
451\index{subtraction}
452
453\section{Shifting operations}
454\indexii{shifting}{operation}
455
456The shifting operations have lower priority than the arithmetic
457operations:
458
459\begin{verbatim}
460shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
461\end{verbatim}
462
463These operators accept plain or long integers as arguments. The
464arguments are converted to a common type. They shift the first
465argument to the left or right by the number of bits given by the
466second argument.
467
468A right shift by $n$ bits is defined as division by $2^n$. A left
469shift by $n$ bits is defined as multiplication with $2^n$; for plain
470integers there is no overflow check so this drops bits and flip the
471sign if the result is not less than $2^{31}$ in absolute value.
472
473Negative shift counts raise a \verb\ValueError\ exception.
474\exindex{ValueError}
475
476\section{Binary bit-wise operations}
477\indexiii{binary}{bit-wise}{operation}
478
479Each of the three bitwise operations has a different priority level:
480
481\begin{verbatim}
482and_expr: shift_expr | and_expr "&" shift_expr
483xor_expr: and_expr | xor_expr "^" and_expr
484or_expr: xor_expr | or_expr "|" xor_expr
485\end{verbatim}
486
487The \verb\"&"\ operator yields the bitwise AND of its arguments, which
488must be plain or long integers. The arguments are converted to a
489common type.
490\indexii{bit-wise}{and}
491
492The \verb\"^"\ operator yields the bitwise XOR (exclusive OR) of its
493arguments, which must be plain or long integers. The arguments are
494converted to a common type.
495\indexii{bit-wise}{xor}
496\indexii{exclusive}{or}
497
498The \verb\"|"\ operator yields the bitwise (inclusive) OR of its
499arguments, which must be plain or long integers. The arguments are
500converted to a common type.
501\indexii{bit-wise}{or}
502\indexii{inclusive}{or}
503
504\section{Comparisons}
505\index{comparison}
506
507Contrary to C, all comparison operations in Python have the same
508priority, which is lower than that of any arithmetic, shifting or
509bitwise operation. Also contrary to C, expressions like
510\verb\a < b < c\ have the interpretation that is conventional in
511mathematics:
512\index{C}
513
514\begin{verbatim}
515comparison: or_expr (comp_operator or_expr)*
516comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
517\end{verbatim}
518
519Comparisons yield integer values: 1 for true, 0 for false.
520
521Comparisons can be chained arbitrarily, e.g. $x < y <= z$ is
522equivalent to $x < y$ \verb\and\ $y <= z$, except that $y$ is
523evaluated only once (but in both cases $z$ is not evaluated at all
524when $x < y$ is found to be false).
525\indexii{chaining}{comparisons}
526
Guido van Rossum4ac605e1992-12-17 15:31:02 +0000527\catcode`\_=8
Guido van Rossum46f3e001992-08-14 09:11:01 +0000528Formally, $e_0 op_1 e_1 op_2 e_2 ...e_{n-1} op_n e_n$ is equivalent to
529$e_0 op_1 e_1$ \verb\and\ $e_1 op_2 e_2$ \verb\and\ ... \verb\and\
530$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
531
532Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
533between $e_0$ and $e_2$, e.g. $x < y > z$ is perfectly legal.
Guido van Rossum4ac605e1992-12-17 15:31:02 +0000534\catcode`\_=12
Guido van Rossum46f3e001992-08-14 09:11:01 +0000535
536The forms \verb\<>\ and \verb\!=\ are equivalent; for consistency with
537C, \verb\!=\ is preferred; where \verb\!=\ is mentioned below
538\verb\<>\ is also implied.
539
540The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
541the values of two objects. The objects needn't have the same type.
542If both are numbers, they are coverted to a common type. Otherwise,
543objects of different types {\em always} compare unequal, and are
544ordered consistently but arbitrarily.
545
546(This unusual definition of comparison is done to simplify the
547definition of operations like sorting and the \verb\in\ and \verb\not
548in\ operators.)
549
550Comparison of objects of the same type depends on the type:
551
552\begin{itemize}
553
554\item
555Numbers are compared arithmetically.
556
557\item
558Strings are compared lexicographically using the numeric equivalents
559(the result of the built-in function \verb\ord\) of their characters.
560
561\item
562Tuples and lists are compared lexicographically using comparison of
563corresponding items.
564
565\item
566Mappings (dictionaries) are compared through lexicographic
567comparison of their sorted (key, value) lists.%
568\footnote{This is expensive since it requires sorting the keys first,
Guido van Rossumb2c65561993-05-12 08:53:36 +0000569but about the only sensible definition. An earlier version of Python
570compared dictionaries by identity only, but this caused surprises
571because people expected to be able to test a dictionary for emptiness
572by comparing it to {\tt \{\}}.}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000573
574\item
575Most other types compare unequal unless they are the same object;
576the choice whether one object is considered smaller or larger than
577another one is made arbitrarily but consistently within one
578execution of a program.
579
580\end{itemize}
581
582The operators \verb\in\ and \verb\not in\ test for sequence
583membership: if $y$ is a sequence, $x ~\verb\in\~ y$ is true if and
584only if there exists an index $i$ such that $x = y[i]$.
585$x ~\verb\not in\~ y$ yields the inverse truth value. The exception
586\verb\TypeError\ is raised when $y$ is not a sequence, or when $y$ is
587a string and $x$ is not a string of length one.%
588\footnote{The latter restriction is sometimes a nuisance.}
589\opindex{in}
590\opindex{not in}
591\indexii{membership}{test}
592\obindex{sequence}
593
594The operators \verb\is\ and \verb\is not\ test for object identity:
595$x ~\verb\is\~ y$ is true if and only if $x$ and $y$ are the same
596object. $x ~\verb\is not\~ y$ yields the inverse truth value.
597\opindex{is}
598\opindex{is not}
599\indexii{identity}{test}
600
601\section{Boolean operations} \label{Booleans}
602\indexii{Boolean}{operation}
603
604Boolean operations have the lowest priority of all Python operations:
605
606\begin{verbatim}
607condition: or_test
608or_test: and_test | or_test "or" and_test
609and_test: not_test | and_test "and" not_test
610not_test: comparison | "not" not_test
611\end{verbatim}
612
613In the context of Boolean operations, and also when conditions are
614used by control flow statements, the following values are interpreted
615as false: \verb\None\, numeric zero of all types, empty sequences
616(strings, tuples and lists), and empty mappings (dictionaries). All
617other values are interpreted as true.
618
619The operator \verb\not\ yields 1 if its argument is false, 0 otherwise.
620\opindex{not}
621
622The condition $x ~\verb\and\~ y$ first evaluates $x$; if $x$ is false,
623its value is returned; otherwise, $y$ is evaluated and the resulting
624value is returned.
625\opindex{and}
626
627The condition $x ~\verb\or\~ y$ first evaluates $x$; if $x$ is true,
628its value is returned; otherwise, $y$ is evaluated and the resulting
629value is returned.
630\opindex{or}
631
632(Note that \verb\and\ and \verb\or\ do not restrict the value and type
633they return to 0 and 1, but rather return the last evaluated argument.
634This is sometimes useful, e.g. if \verb\s\ is a string that should be
635replaced by a default value if it is empty, the expression
636\verb\s or 'foo'\ yields the desired value. Because \verb\not\ has to
637invent a value anyway, it does not bother to return a value of the
638same type as its argument, so e.g. \verb\not 'foo'\ yields \verb\0\,
639not \verb\''\.)
640
641\section{Expression lists and condition lists}
642\indexii{expression}{list}
643\indexii{condition}{list}
644
645\begin{verbatim}
646expr_list: or_expr ("," or_expr)* [","]
647cond_list: condition ("," condition)* [","]
648\end{verbatim}
649
650The only difference between expression lists and condition lists is
651the lowest priority of operators that can be used in them without
652being enclosed in parentheses; condition lists allow all operators,
653while expression lists don't allow comparisons and Boolean operators
654(they do allow bitwise and shift operators though).
655
656Expression lists are used in expression statements and assignments;
657condition lists are used everywhere else where a list of
658comma-separated values is required.
659
660An expression (condition) list containing at least one comma yields a
661tuple. The length of the tuple is the number of expressions
662(conditions) in the list. The expressions (conditions) are evaluated
663from left to right. (Conditions lists are used syntactically is a few
664places where no tuple is constructed but a list of values is needed
665nevertheless.)
666\obindex{tuple}
667
668The trailing comma is required only to create a single tuple (a.k.a. a
669{\em singleton}); it is optional in all other cases. A single
670expression (condition) without a trailing comma doesn't create a
671tuple, but rather yields the value of that expression (condition).
672\indexii{trailing}{comma}
673
674(To create an empty tuple, use an empty pair of parentheses:
675\verb\()\.)