Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | .. _expressions: |
| 3 | |
| 4 | *********** |
| 5 | Expressions |
| 6 | *********** |
| 7 | |
| 8 | .. index:: single: expression |
| 9 | |
| 10 | This chapter explains the meaning of the elements of expressions in Python. |
| 11 | |
| 12 | .. index:: single: BNF |
| 13 | |
| 14 | **Syntax Notes:** In this and the following chapters, extended BNF notation will |
| 15 | be used to describe syntax, not lexical analysis. When (one alternative of) a |
| 16 | syntax rule has the form |
| 17 | |
| 18 | .. productionlist:: * |
| 19 | name: `othername` |
| 20 | |
| 21 | .. index:: single: syntax |
| 22 | |
| 23 | and no semantics are given, the semantics of this form of ``name`` are the same |
| 24 | as for ``othername``. |
| 25 | |
| 26 | |
| 27 | .. _conversions: |
| 28 | |
| 29 | Arithmetic conversions |
| 30 | ====================== |
| 31 | |
| 32 | .. index:: pair: arithmetic; conversion |
| 33 | |
| 34 | .. XXX no coercion rules are documented anymore |
| 35 | |
| 36 | When a description of an arithmetic operator below uses the phrase "the numeric |
| 37 | arguments are converted to a common type," the arguments are coerced using the |
| 38 | coercion rules. If both arguments are standard |
| 39 | numeric types, the following coercions are applied: |
| 40 | |
| 41 | * If either argument is a complex number, the other is converted to complex; |
| 42 | |
| 43 | * otherwise, if either argument is a floating point number, the other is |
| 44 | converted to floating point; |
| 45 | |
| 46 | * otherwise, if either argument is a long integer, the other is converted to |
| 47 | long integer; |
| 48 | |
| 49 | * otherwise, both must be plain integers and no conversion is necessary. |
| 50 | |
| 51 | Some additional rules apply for certain operators (e.g., a string left argument |
| 52 | to the '%' operator). Extensions can define their own coercions. |
| 53 | |
| 54 | |
| 55 | .. _atoms: |
| 56 | |
| 57 | Atoms |
| 58 | ===== |
| 59 | |
| 60 | .. index:: single: atom |
| 61 | |
| 62 | Atoms are the most basic elements of expressions. The simplest atoms are |
| 63 | identifiers or literals. Forms enclosed in reverse quotes or in parentheses, |
| 64 | brackets or braces are also categorized syntactically as atoms. The syntax for |
| 65 | atoms is: |
| 66 | |
| 67 | .. productionlist:: |
| 68 | atom: `identifier` | `literal` | `enclosure` |
| 69 | enclosure: `parenth_form` | `list_display` |
| 70 | : | `generator_expression` | `dict_display` |
| 71 | : | `string_conversion` | `yield_atom` |
| 72 | |
| 73 | |
| 74 | .. _atom-identifiers: |
| 75 | |
| 76 | Identifiers (Names) |
| 77 | ------------------- |
| 78 | |
| 79 | .. index:: |
| 80 | single: name |
| 81 | single: identifier |
| 82 | |
| 83 | An identifier occurring as an atom is a name. See section :ref:`identifiers` |
| 84 | for lexical definition and section :ref:`naming` for documentation of naming and |
| 85 | binding. |
| 86 | |
| 87 | .. index:: exception: NameError |
| 88 | |
| 89 | When the name is bound to an object, evaluation of the atom yields that object. |
| 90 | When a name is not bound, an attempt to evaluate it raises a :exc:`NameError` |
| 91 | exception. |
| 92 | |
| 93 | .. index:: |
| 94 | pair: name; mangling |
| 95 | pair: private; names |
| 96 | |
| 97 | **Private name mangling:** When an identifier that textually occurs in a class |
| 98 | definition begins with two or more underscore characters and does not end in two |
| 99 | or more underscores, it is considered a :dfn:`private name` of that class. |
| 100 | Private names are transformed to a longer form before code is generated for |
| 101 | them. The transformation inserts the class name in front of the name, with |
| 102 | leading underscores removed, and a single underscore inserted in front of the |
| 103 | class name. For example, the identifier ``__spam`` occurring in a class named |
| 104 | ``Ham`` will be transformed to ``_Ham__spam``. This transformation is |
| 105 | independent of the syntactical context in which the identifier is used. If the |
| 106 | transformed name is extremely long (longer than 255 characters), implementation |
| 107 | defined truncation may happen. If the class name consists only of underscores, |
| 108 | no transformation is done. |
| 109 | |
| 110 | .. % |
| 111 | .. % |
| 112 | |
| 113 | |
| 114 | .. _atom-literals: |
| 115 | |
| 116 | Literals |
| 117 | -------- |
| 118 | |
| 119 | .. index:: single: literal |
| 120 | |
| 121 | Python supports string literals and various numeric literals: |
| 122 | |
| 123 | .. productionlist:: |
| 124 | literal: `stringliteral` | `integer` | `longinteger` |
| 125 | : | `floatnumber` | `imagnumber` |
| 126 | |
| 127 | Evaluation of a literal yields an object of the given type (string, integer, |
| 128 | long integer, floating point number, complex number) with the given value. The |
| 129 | value may be approximated in the case of floating point and imaginary (complex) |
| 130 | literals. See section :ref:`literals` for details. |
| 131 | |
| 132 | .. index:: |
| 133 | triple: immutable; data; type |
| 134 | pair: immutable; object |
| 135 | |
| 136 | All literals correspond to immutable data types, and hence the object's identity |
| 137 | is less important than its value. Multiple evaluations of literals with the |
| 138 | same value (either the same occurrence in the program text or a different |
| 139 | occurrence) may obtain the same object or a different object with the same |
| 140 | value. |
| 141 | |
| 142 | |
| 143 | .. _parenthesized: |
| 144 | |
| 145 | Parenthesized forms |
| 146 | ------------------- |
| 147 | |
| 148 | .. index:: single: parenthesized form |
| 149 | |
| 150 | A parenthesized form is an optional expression list enclosed in parentheses: |
| 151 | |
| 152 | .. productionlist:: |
| 153 | parenth_form: "(" [`expression_list`] ")" |
| 154 | |
| 155 | A parenthesized expression list yields whatever that expression list yields: if |
| 156 | the list contains at least one comma, it yields a tuple; otherwise, it yields |
| 157 | the single expression that makes up the expression list. |
| 158 | |
| 159 | .. index:: pair: empty; tuple |
| 160 | |
| 161 | An empty pair of parentheses yields an empty tuple object. Since tuples are |
| 162 | immutable, the rules for literals apply (i.e., two occurrences of the empty |
| 163 | tuple may or may not yield the same object). |
| 164 | |
| 165 | .. index:: |
| 166 | single: comma |
| 167 | pair: tuple; display |
| 168 | |
| 169 | Note that tuples are not formed by the parentheses, but rather by use of the |
| 170 | comma operator. The exception is the empty tuple, for which parentheses *are* |
| 171 | required --- allowing unparenthesized "nothing" in expressions would cause |
| 172 | ambiguities and allow common typos to pass uncaught. |
| 173 | |
| 174 | |
| 175 | .. _lists: |
| 176 | |
| 177 | List displays |
| 178 | ------------- |
| 179 | |
| 180 | .. index:: |
| 181 | pair: list; display |
| 182 | pair: list; comprehensions |
| 183 | |
| 184 | A list display is a possibly empty series of expressions enclosed in square |
| 185 | brackets: |
| 186 | |
| 187 | .. productionlist:: |
| 188 | list_display: "[" [`expression_list` | `list_comprehension`] "]" |
| 189 | list_comprehension: `expression` `list_for` |
| 190 | list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`] |
| 191 | old_expression_list: `old_expression` [("," `old_expression`)+ [","]] |
| 192 | list_iter: `list_for` | `list_if` |
| 193 | list_if: "if" `old_expression` [`list_iter`] |
| 194 | |
| 195 | .. index:: |
| 196 | pair: list; comprehensions |
| 197 | object: list |
| 198 | pair: empty; list |
| 199 | |
| 200 | A list display yields a new list object. Its contents are specified by |
| 201 | providing either a list of expressions or a list comprehension. When a |
| 202 | comma-separated list of expressions is supplied, its elements are evaluated from |
| 203 | left to right and placed into the list object in that order. When a list |
| 204 | comprehension is supplied, it consists of a single expression followed by at |
| 205 | least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` |
| 206 | clauses. In this case, the elements of the new list are those that would be |
| 207 | produced by considering each of the :keyword:`for` or :keyword:`if` clauses a |
| 208 | block, nesting from left to right, and evaluating the expression to produce a |
| 209 | list element each time the innermost block is reached [#]_. |
| 210 | |
| 211 | |
| 212 | .. _genexpr: |
| 213 | |
| 214 | Generator expressions |
| 215 | --------------------- |
| 216 | |
| 217 | .. index:: pair: generator; expression |
| 218 | |
| 219 | A generator expression is a compact generator notation in parentheses: |
| 220 | |
| 221 | .. productionlist:: |
| 222 | generator_expression: "(" `expression` `genexpr_for` ")" |
| 223 | genexpr_for: "for" `target_list` "in" `or_test` [`genexpr_iter`] |
| 224 | genexpr_iter: `genexpr_for` | `genexpr_if` |
| 225 | genexpr_if: "if" `old_expression` [`genexpr_iter`] |
| 226 | |
| 227 | .. index:: object: generator |
| 228 | |
| 229 | A generator expression yields a new generator object. It consists of a single |
| 230 | expression followed by at least one :keyword:`for` clause and zero or more |
| 231 | :keyword:`for` or :keyword:`if` clauses. The iterating values of the new |
| 232 | generator are those that would be produced by considering each of the |
| 233 | :keyword:`for` or :keyword:`if` clauses a block, nesting from left to right, and |
| 234 | evaluating the expression to yield a value that is reached the innermost block |
| 235 | for each iteration. |
| 236 | |
| 237 | Variables used in the generator expression are evaluated lazily when the |
| 238 | :meth:`__next__` method is called for generator object (in the same fashion as |
| 239 | normal generators). However, the leftmost :keyword:`for` clause is immediately |
| 240 | evaluated so that error produced by it can be seen before any other possible |
| 241 | error in the code that handles the generator expression. Subsequent |
| 242 | :keyword:`for` clauses cannot be evaluated immediately since they may depend on |
| 243 | the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y |
| 244 | in bar(x))``. |
| 245 | |
| 246 | The parentheses can be omitted on calls with only one argument. See section |
| 247 | :ref:`calls` for the detail. |
| 248 | |
| 249 | |
| 250 | .. _dict: |
| 251 | |
| 252 | Dictionary displays |
| 253 | ------------------- |
| 254 | |
| 255 | .. index:: pair: dictionary; display |
| 256 | |
| 257 | .. index:: |
| 258 | single: key |
| 259 | single: datum |
| 260 | single: key/datum pair |
| 261 | |
| 262 | A dictionary display is a possibly empty series of key/datum pairs enclosed in |
| 263 | curly braces: |
| 264 | |
| 265 | .. productionlist:: |
| 266 | dict_display: "{" [`key_datum_list`] "}" |
| 267 | key_datum_list: `key_datum` ("," `key_datum`)* [","] |
| 268 | key_datum: `expression` ":" `expression` |
| 269 | |
| 270 | .. index:: object: dictionary |
| 271 | |
| 272 | A dictionary display yields a new dictionary object. |
| 273 | |
| 274 | The key/datum pairs are evaluated from left to right to define the entries of |
| 275 | the dictionary: each key object is used as a key into the dictionary to store |
| 276 | the corresponding datum. |
| 277 | |
| 278 | .. index:: pair: immutable; object |
| 279 | |
| 280 | Restrictions on the types of the key values are listed earlier in section |
| 281 | :ref:`types`. (To summarize, the key type should be hashable, which excludes |
| 282 | all mutable objects.) Clashes between duplicate keys are not detected; the last |
| 283 | datum (textually rightmost in the display) stored for a given key value |
| 284 | prevails. |
| 285 | |
| 286 | |
| 287 | .. _yieldexpr: |
| 288 | |
| 289 | Yield expressions |
| 290 | ----------------- |
| 291 | |
| 292 | .. index:: |
| 293 | keyword: yield |
| 294 | pair: yield; expression |
| 295 | pair: generator; function |
| 296 | |
| 297 | .. productionlist:: |
| 298 | yield_atom: "(" `yield_expression` ")" |
| 299 | yield_expression: "yield" [`expression_list`] |
| 300 | |
| 301 | .. versionadded:: 2.5 |
| 302 | |
| 303 | The :keyword:`yield` expression is only used when defining a generator function, |
| 304 | and can only be used in the body of a function definition. Using a |
| 305 | :keyword:`yield` expression in a function definition is sufficient to cause that |
| 306 | definition to create a generator function instead of a normal function. |
| 307 | |
| 308 | When a generator function is called, it returns an iterator known as a |
| 309 | generator. That generator then controls the execution of a generator function. |
| 310 | The execution starts when one of the generator's methods is called. At that |
| 311 | time, the execution proceeds to the first :keyword:`yield` expression, where it |
| 312 | is suspended again, returning the value of :token:`expression_list` to |
| 313 | generator's caller. By suspended we mean that all local state is retained, |
| 314 | including the current bindings of local variables, the instruction pointer, and |
| 315 | the internal evaluation stack. When the execution is resumed by calling one of |
| 316 | the generator's methods, the function can proceed exactly as if the |
| 317 | :keyword:`yield` expression was just another external call. The value of the |
| 318 | :keyword:`yield` expression after resuming depends on the method which resumed |
| 319 | the execution. |
| 320 | |
| 321 | .. index:: single: coroutine |
| 322 | |
| 323 | All of this makes generator functions quite similar to coroutines; they yield |
| 324 | multiple times, they have more than one entry point and their execution can be |
| 325 | suspended. The only difference is that a generator function cannot control |
| 326 | where should the execution continue after it yields; the control is always |
| 327 | transfered to the generator's caller. |
| 328 | |
| 329 | .. index:: object: generator |
| 330 | |
| 331 | The following generator's methods can be used to control the execution of a |
| 332 | generator function: |
| 333 | |
| 334 | .. index:: exception: StopIteration |
| 335 | |
| 336 | |
| 337 | .. method:: generator.next() |
| 338 | |
| 339 | Starts the execution of a generator function or resumes it at the last executed |
| 340 | :keyword:`yield` expression. When a generator function is resumed with a |
| 341 | :meth:`next` method, the current :keyword:`yield` expression always evaluates to |
| 342 | :const:`None`. The execution then continues to the next :keyword:`yield` |
| 343 | expression, where the generator is suspended again, and the value of the |
| 344 | :token:`expression_list` is returned to :meth:`next`'s caller. If the generator |
| 345 | exits without yielding another value, a :exc:`StopIteration` exception is |
| 346 | raised. |
| 347 | |
| 348 | |
| 349 | .. method:: generator.send(value) |
| 350 | |
| 351 | Resumes the execution and "sends" a value into the generator function. The |
| 352 | ``value`` argument becomes the result of the current :keyword:`yield` |
| 353 | expression. The :meth:`send` method returns the next value yielded by the |
| 354 | generator, or raises :exc:`StopIteration` if the generator exits without |
| 355 | yielding another value. When :meth:`send` is called to start the generator, it |
| 356 | must be called with :const:`None` as the argument, because there is no |
| 357 | :keyword:`yield` expression that could receieve the value. |
| 358 | |
| 359 | |
| 360 | .. method:: generator.throw(type[, value[, traceback]]) |
| 361 | |
| 362 | Raises an exception of type ``type`` at the point where generator was paused, |
| 363 | and returns the next value yielded by the generator function. If the generator |
| 364 | exits without yielding another value, a :exc:`StopIteration` exception is |
| 365 | raised. If the generator function does not catch the passed-in exception, or |
| 366 | raises a different exception, then that exception propagates to the caller. |
| 367 | |
| 368 | .. index:: exception: GeneratorExit |
| 369 | |
| 370 | |
| 371 | .. method:: generator.close() |
| 372 | |
| 373 | Raises a :exc:`GeneratorExit` at the point where the generator function was |
| 374 | paused. If the generator function then raises :exc:`StopIteration` (by exiting |
| 375 | normally, or due to already being closed) or :exc:`GeneratorExit` (by not |
| 376 | catching the exception), close returns to its caller. If the generator yields a |
| 377 | value, a :exc:`RuntimeError` is raised. If the generator raises any other |
| 378 | exception, it is propagated to the caller. :meth:`close` does nothing if the |
| 379 | generator has already exited due to an exception or normal exit. |
| 380 | |
| 381 | Here is a simple example that demonstrates the behavior of generators and |
| 382 | generator functions:: |
| 383 | |
| 384 | >>> def echo(value=None): |
| 385 | ... print "Execution starts when 'next()' is called for the first time." |
| 386 | ... try: |
| 387 | ... while True: |
| 388 | ... try: |
| 389 | ... value = (yield value) |
| 390 | ... except GeneratorExit: |
| 391 | ... # never catch GeneratorExit |
| 392 | ... raise |
| 393 | ... except Exception, e: |
| 394 | ... value = e |
| 395 | ... finally: |
| 396 | ... print "Don't forget to clean up when 'close()' is called." |
| 397 | ... |
| 398 | >>> generator = echo(1) |
| 399 | >>> print generator.next() |
| 400 | Execution starts when 'next()' is called for the first time. |
| 401 | 1 |
| 402 | >>> print generator.next() |
| 403 | None |
| 404 | >>> print generator.send(2) |
| 405 | 2 |
| 406 | >>> generator.throw(TypeError, "spam") |
| 407 | TypeError('spam',) |
| 408 | >>> generator.close() |
| 409 | Don't forget to clean up when 'close()' is called. |
| 410 | |
| 411 | |
| 412 | .. seealso:: |
| 413 | |
| 414 | :pep:`0342` - Coroutines via Enhanced Generators |
| 415 | The proposal to enhance the API and syntax of generators, making them usable as |
| 416 | simple coroutines. |
| 417 | |
| 418 | |
| 419 | .. _primaries: |
| 420 | |
| 421 | Primaries |
| 422 | ========= |
| 423 | |
| 424 | .. index:: single: primary |
| 425 | |
| 426 | Primaries represent the most tightly bound operations of the language. Their |
| 427 | syntax is: |
| 428 | |
| 429 | .. productionlist:: |
| 430 | primary: `atom` | `attributeref` | `subscription` | `slicing` | `call` |
| 431 | |
| 432 | |
| 433 | .. _attribute-references: |
| 434 | |
| 435 | Attribute references |
| 436 | -------------------- |
| 437 | |
| 438 | .. index:: pair: attribute; reference |
| 439 | |
| 440 | An attribute reference is a primary followed by a period and a name: |
| 441 | |
| 442 | .. productionlist:: |
| 443 | attributeref: `primary` "." `identifier` |
| 444 | |
| 445 | .. index:: |
| 446 | exception: AttributeError |
| 447 | object: module |
| 448 | object: list |
| 449 | |
| 450 | The primary must evaluate to an object of a type that supports attribute |
| 451 | references, e.g., a module, list, or an instance. This object is then asked to |
| 452 | produce the attribute whose name is the identifier. If this attribute is not |
| 453 | available, the exception :exc:`AttributeError` is raised. Otherwise, the type |
| 454 | and value of the object produced is determined by the object. Multiple |
| 455 | evaluations of the same attribute reference may yield different objects. |
| 456 | |
| 457 | |
| 458 | .. _subscriptions: |
| 459 | |
| 460 | Subscriptions |
| 461 | ------------- |
| 462 | |
| 463 | .. index:: single: subscription |
| 464 | |
| 465 | .. index:: |
| 466 | object: sequence |
| 467 | object: mapping |
| 468 | object: string |
| 469 | object: tuple |
| 470 | object: list |
| 471 | object: dictionary |
| 472 | pair: sequence; item |
| 473 | |
| 474 | A subscription selects an item of a sequence (string, tuple or list) or mapping |
| 475 | (dictionary) object: |
| 476 | |
| 477 | .. productionlist:: |
| 478 | subscription: `primary` "[" `expression_list` "]" |
| 479 | |
| 480 | The primary must evaluate to an object of a sequence or mapping type. |
| 481 | |
| 482 | If the primary is a mapping, the expression list must evaluate to an object |
| 483 | whose value is one of the keys of the mapping, and the subscription selects the |
| 484 | value in the mapping that corresponds to that key. (The expression list is a |
| 485 | tuple except if it has exactly one item.) |
| 486 | |
| 487 | If the primary is a sequence, the expression (list) must evaluate to a plain |
| 488 | integer. If this value is negative, the length of the sequence is added to it |
| 489 | (so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value |
| 490 | must be a nonnegative integer less than the number of items in the sequence, and |
| 491 | the subscription selects the item whose index is that value (counting from |
| 492 | zero). |
| 493 | |
| 494 | .. index:: |
| 495 | single: character |
| 496 | pair: string; item |
| 497 | |
| 498 | A string's items are characters. A character is not a separate data type but a |
| 499 | string of exactly one character. |
| 500 | |
| 501 | |
| 502 | .. _slicings: |
| 503 | |
| 504 | Slicings |
| 505 | -------- |
| 506 | |
| 507 | .. index:: |
| 508 | single: slicing |
| 509 | single: slice |
| 510 | |
| 511 | .. index:: |
| 512 | object: sequence |
| 513 | object: string |
| 514 | object: tuple |
| 515 | object: list |
| 516 | |
| 517 | A slicing selects a range of items in a sequence object (e.g., a string, tuple |
| 518 | or list). Slicings may be used as expressions or as targets in assignment or |
| 519 | :keyword:`del` statements. The syntax for a slicing: |
| 520 | |
| 521 | .. productionlist:: |
| 522 | slicing: `simple_slicing` | `extended_slicing` |
| 523 | simple_slicing: `primary` "[" `short_slice` "]" |
| 524 | extended_slicing: `primary` "[" `slice_list` "]" |
| 525 | slice_list: `slice_item` ("," `slice_item`)* [","] |
| 526 | slice_item: `expression` | `proper_slice` | `ellipsis` |
| 527 | proper_slice: `short_slice` | `long_slice` |
| 528 | short_slice: [`lower_bound`] ":" [`upper_bound`] |
| 529 | long_slice: `short_slice` ":" [`stride`] |
| 530 | lower_bound: `expression` |
| 531 | upper_bound: `expression` |
| 532 | stride: `expression` |
| 533 | ellipsis: "..." |
| 534 | |
| 535 | .. index:: pair: extended; slicing |
| 536 | |
| 537 | There is ambiguity in the formal syntax here: anything that looks like an |
| 538 | expression list also looks like a slice list, so any subscription can be |
| 539 | interpreted as a slicing. Rather than further complicating the syntax, this is |
| 540 | disambiguated by defining that in this case the interpretation as a subscription |
| 541 | takes priority over the interpretation as a slicing (this is the case if the |
| 542 | slice list contains no proper slice nor ellipses). Similarly, when the slice |
| 543 | list has exactly one short slice and no trailing comma, the interpretation as a |
| 544 | simple slicing takes priority over that as an extended slicing. |
| 545 | |
| 546 | The semantics for a simple slicing are as follows. The primary must evaluate to |
| 547 | a sequence object. The lower and upper bound expressions, if present, must |
| 548 | evaluate to plain integers; defaults are zero and the ``sys.maxint``, |
| 549 | respectively. If either bound is negative, the sequence's length is added to |
| 550 | it. The slicing now selects all items with index *k* such that ``i <= k < j`` |
| 551 | where *i* and *j* are the specified lower and upper bounds. This may be an |
| 552 | empty sequence. It is not an error if *i* or *j* lie outside the range of valid |
| 553 | indexes (such items don't exist so they aren't selected). |
| 554 | |
| 555 | .. index:: |
| 556 | single: start (slice object attribute) |
| 557 | single: stop (slice object attribute) |
| 558 | single: step (slice object attribute) |
| 559 | |
| 560 | The semantics for an extended slicing are as follows. The primary must evaluate |
| 561 | to a mapping object, and it is indexed with a key that is constructed from the |
| 562 | slice list, as follows. If the slice list contains at least one comma, the key |
| 563 | is a tuple containing the conversion of the slice items; otherwise, the |
| 564 | conversion of the lone slice item is the key. The conversion of a slice item |
| 565 | that is an expression is that expression. The conversion of a proper slice is a |
| 566 | slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and |
| 567 | :attr:`step` attributes are the values of the expressions given as lower bound, |
| 568 | upper bound and stride, respectively, substituting ``None`` for missing |
| 569 | expressions. |
| 570 | |
| 571 | |
| 572 | .. _calls: |
| 573 | |
| 574 | Calls |
| 575 | ----- |
| 576 | |
| 577 | .. index:: single: call |
| 578 | |
| 579 | .. index:: object: callable |
| 580 | |
| 581 | A call calls a callable object (e.g., a function) with a possibly empty series |
| 582 | of arguments: |
| 583 | |
| 584 | .. productionlist:: |
| 585 | call: `primary` "(" [`argument_list` [","] |
| 586 | : | `expression` `genexpr_for`] ")" |
| 587 | argument_list: `positional_arguments` ["," `keyword_arguments`] |
| 588 | : ["," "*" `expression`] |
| 589 | : ["," "**" `expression`] |
| 590 | : | `keyword_arguments` ["," "*" `expression`] |
| 591 | : ["," "**" `expression`] |
| 592 | : | "*" `expression` ["," "**" `expression`] |
| 593 | : | "**" `expression` |
| 594 | positional_arguments: `expression` ("," `expression`)* |
| 595 | keyword_arguments: `keyword_item` ("," `keyword_item`)* |
| 596 | keyword_item: `identifier` "=" `expression` |
| 597 | |
| 598 | A trailing comma may be present after the positional and keyword arguments but |
| 599 | does not affect the semantics. |
| 600 | |
| 601 | The primary must evaluate to a callable object (user-defined functions, built-in |
| 602 | functions, methods of built-in objects, class objects, methods of class |
| 603 | instances, and certain class instances themselves are callable; extensions may |
| 604 | define additional callable object types). All argument expressions are |
| 605 | evaluated before the call is attempted. Please refer to section :ref:`function` |
| 606 | for the syntax of formal parameter lists. |
| 607 | |
| 608 | If keyword arguments are present, they are first converted to positional |
| 609 | arguments, as follows. First, a list of unfilled slots is created for the |
| 610 | formal parameters. If there are N positional arguments, they are placed in the |
| 611 | first N slots. Next, for each keyword argument, the identifier is used to |
| 612 | determine the corresponding slot (if the identifier is the same as the first |
| 613 | formal parameter name, the first slot is used, and so on). If the slot is |
| 614 | already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of |
| 615 | the argument is placed in the slot, filling it (even if the expression is |
| 616 | ``None``, it fills the slot). When all arguments have been processed, the slots |
| 617 | that are still unfilled are filled with the corresponding default value from the |
| 618 | function definition. (Default values are calculated, once, when the function is |
| 619 | defined; thus, a mutable object such as a list or dictionary used as default |
| 620 | value will be shared by all calls that don't specify an argument value for the |
| 621 | corresponding slot; this should usually be avoided.) If there are any unfilled |
| 622 | slots for which no default value is specified, a :exc:`TypeError` exception is |
| 623 | raised. Otherwise, the list of filled slots is used as the argument list for |
| 624 | the call. |
| 625 | |
| 626 | If there are more positional arguments than there are formal parameter slots, a |
| 627 | :exc:`TypeError` exception is raised, unless a formal parameter using the syntax |
| 628 | ``*identifier`` is present; in this case, that formal parameter receives a tuple |
| 629 | containing the excess positional arguments (or an empty tuple if there were no |
| 630 | excess positional arguments). |
| 631 | |
| 632 | If any keyword argument does not correspond to a formal parameter name, a |
| 633 | :exc:`TypeError` exception is raised, unless a formal parameter using the syntax |
| 634 | ``**identifier`` is present; in this case, that formal parameter receives a |
| 635 | dictionary containing the excess keyword arguments (using the keywords as keys |
| 636 | and the argument values as corresponding values), or a (new) empty dictionary if |
| 637 | there were no excess keyword arguments. |
| 638 | |
| 639 | If the syntax ``*expression`` appears in the function call, ``expression`` must |
| 640 | evaluate to a sequence. Elements from this sequence are treated as if they were |
| 641 | additional positional arguments; if there are postional arguments *x1*,...,*xN* |
| 642 | , and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent |
| 643 | to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*. |
| 644 | |
| 645 | A consequence of this is that although the ``*expression`` syntax appears |
| 646 | *after* any keyword arguments, it is processed *before* the keyword arguments |
| 647 | (and the ``**expression`` argument, if any -- see below). So:: |
| 648 | |
| 649 | >>> def f(a, b): |
| 650 | ... print a, b |
| 651 | ... |
| 652 | >>> f(b=1, *(2,)) |
| 653 | 2 1 |
| 654 | >>> f(a=1, *(2,)) |
| 655 | Traceback (most recent call last): |
| 656 | File "<stdin>", line 1, in ? |
| 657 | TypeError: f() got multiple values for keyword argument 'a' |
| 658 | >>> f(1, *(2,)) |
| 659 | 1 2 |
| 660 | |
| 661 | It is unusual for both keyword arguments and the ``*expression`` syntax to be |
| 662 | used in the same call, so in practice this confusion does not arise. |
| 663 | |
| 664 | If the syntax ``**expression`` appears in the function call, ``expression`` must |
| 665 | evaluate to a mapping, the contents of which are treated as additional keyword |
| 666 | arguments. In the case of a keyword appearing in both ``expression`` and as an |
| 667 | explicit keyword argument, a :exc:`TypeError` exception is raised. |
| 668 | |
| 669 | Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be |
| 670 | used as positional argument slots or as keyword argument names. |
| 671 | |
| 672 | A call always returns some value, possibly ``None``, unless it raises an |
| 673 | exception. How this value is computed depends on the type of the callable |
| 674 | object. |
| 675 | |
| 676 | If it is--- |
| 677 | |
| 678 | a user-defined function: |
| 679 | .. index:: |
| 680 | pair: function; call |
| 681 | triple: user-defined; function; call |
| 682 | object: user-defined function |
| 683 | object: function |
| 684 | |
| 685 | The code block for the function is executed, passing it the argument list. The |
| 686 | first thing the code block will do is bind the formal parameters to the |
| 687 | arguments; this is described in section :ref:`function`. When the code block |
| 688 | executes a :keyword:`return` statement, this specifies the return value of the |
| 689 | function call. |
| 690 | |
| 691 | a built-in function or method: |
| 692 | .. index:: |
| 693 | pair: function; call |
| 694 | pair: built-in function; call |
| 695 | pair: method; call |
| 696 | pair: built-in method; call |
| 697 | object: built-in method |
| 698 | object: built-in function |
| 699 | object: method |
| 700 | object: function |
| 701 | |
| 702 | The result is up to the interpreter; see :ref:`built-in-funcs` for the |
| 703 | descriptions of built-in functions and methods. |
| 704 | |
| 705 | a class object: |
| 706 | .. index:: |
| 707 | object: class |
| 708 | pair: class object; call |
| 709 | |
| 710 | A new instance of that class is returned. |
| 711 | |
| 712 | a class instance method: |
| 713 | .. index:: |
| 714 | object: class instance |
| 715 | object: instance |
| 716 | pair: class instance; call |
| 717 | |
| 718 | The corresponding user-defined function is called, with an argument list that is |
| 719 | one longer than the argument list of the call: the instance becomes the first |
| 720 | argument. |
| 721 | |
| 722 | a class instance: |
| 723 | .. index:: |
| 724 | pair: instance; call |
| 725 | single: __call__() (object method) |
| 726 | |
| 727 | The class must define a :meth:`__call__` method; the effect is then the same as |
| 728 | if that method was called. |
| 729 | |
| 730 | |
| 731 | .. _power: |
| 732 | |
| 733 | The power operator |
| 734 | ================== |
| 735 | |
| 736 | The power operator binds more tightly than unary operators on its left; it binds |
| 737 | less tightly than unary operators on its right. The syntax is: |
| 738 | |
| 739 | .. productionlist:: |
| 740 | power: `primary` ["**" `u_expr`] |
| 741 | |
| 742 | Thus, in an unparenthesized sequence of power and unary operators, the operators |
| 743 | are evaluated from right to left (this does not constrain the evaluation order |
| 744 | for the operands). |
| 745 | |
| 746 | The power operator has the same semantics as the built-in :func:`pow` function, |
| 747 | when called with two arguments: it yields its left argument raised to the power |
| 748 | of its right argument. The numeric arguments are first converted to a common |
| 749 | type. The result type is that of the arguments after coercion. |
| 750 | |
| 751 | With mixed operand types, the coercion rules for binary arithmetic operators |
| 752 | apply. For int and long int operands, the result has the same type as the |
| 753 | operands (after coercion) unless the second argument is negative; in that case, |
| 754 | all arguments are converted to float and a float result is delivered. For |
| 755 | example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last |
| 756 | feature was added in Python 2.2. In Python 2.1 and before, if both arguments |
| 757 | were of integer types and the second argument was negative, an exception was |
| 758 | raised). |
| 759 | |
| 760 | Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`. |
| 761 | Raising a negative number to a fractional power results in a :exc:`ValueError`. |
| 762 | |
| 763 | |
| 764 | .. _unary: |
| 765 | |
| 766 | Unary arithmetic operations |
| 767 | =========================== |
| 768 | |
| 769 | .. index:: |
| 770 | triple: unary; arithmetic; operation |
| 771 | triple: unary; bit-wise; operation |
| 772 | |
| 773 | All unary arithmetic (and bit-wise) operations have the same priority: |
| 774 | |
| 775 | .. productionlist:: |
| 776 | u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr` |
| 777 | |
| 778 | .. index:: |
| 779 | single: negation |
| 780 | single: minus |
| 781 | |
| 782 | The unary ``-`` (minus) operator yields the negation of its numeric argument. |
| 783 | |
| 784 | .. index:: single: plus |
| 785 | |
| 786 | The unary ``+`` (plus) operator yields its numeric argument unchanged. |
| 787 | |
| 788 | .. index:: single: inversion |
| 789 | |
| 790 | The unary ``~`` (invert) operator yields the bit-wise inversion of its plain or |
| 791 | long integer argument. The bit-wise inversion of ``x`` is defined as |
| 792 | ``-(x+1)``. It only applies to integral numbers. |
| 793 | |
| 794 | .. index:: exception: TypeError |
| 795 | |
| 796 | In all three cases, if the argument does not have the proper type, a |
| 797 | :exc:`TypeError` exception is raised. |
| 798 | |
| 799 | |
| 800 | .. _binary: |
| 801 | |
| 802 | Binary arithmetic operations |
| 803 | ============================ |
| 804 | |
| 805 | .. index:: triple: binary; arithmetic; operation |
| 806 | |
| 807 | The binary arithmetic operations have the conventional priority levels. Note |
| 808 | that some of these operations also apply to certain non-numeric types. Apart |
| 809 | from the power operator, there are only two levels, one for multiplicative |
| 810 | operators and one for additive operators: |
| 811 | |
| 812 | .. productionlist:: |
| 813 | m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
| 814 | : | `m_expr` "%" `u_expr` |
| 815 | a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr` |
| 816 | |
| 817 | .. index:: single: multiplication |
| 818 | |
| 819 | The ``*`` (multiplication) operator yields the product of its arguments. The |
| 820 | arguments must either both be numbers, or one argument must be an integer (plain |
| 821 | or long) and the other must be a sequence. In the former case, the numbers are |
| 822 | converted to a common type and then multiplied together. In the latter case, |
| 823 | sequence repetition is performed; a negative repetition factor yields an empty |
| 824 | sequence. |
| 825 | |
| 826 | .. index:: |
| 827 | exception: ZeroDivisionError |
| 828 | single: division |
| 829 | |
| 830 | The ``/`` (division) and ``//`` (floor division) operators yield the quotient of |
| 831 | their arguments. The numeric arguments are first converted to a common type. |
| 832 | Plain or long integer division yields an integer of the same type; the result is |
| 833 | that of mathematical division with the 'floor' function applied to the result. |
| 834 | Division by zero raises the :exc:`ZeroDivisionError` exception. |
| 835 | |
| 836 | .. index:: single: modulo |
| 837 | |
| 838 | The ``%`` (modulo) operator yields the remainder from the division of the first |
| 839 | argument by the second. The numeric arguments are first converted to a common |
| 840 | type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The |
| 841 | arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34`` |
| 842 | (since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a |
| 843 | result with the same sign as its second operand (or zero); the absolute value of |
| 844 | the result is strictly smaller than the absolute value of the second operand |
| 845 | [#]_. |
| 846 | |
| 847 | The integer division and modulo operators are connected by the following |
| 848 | identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also |
| 849 | connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y, |
| 850 | x%y)``. These identities don't hold for floating point numbers; there similar |
| 851 | identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or |
| 852 | ``floor(x/y) - 1`` [#]_. |
| 853 | |
| 854 | In addition to performing the modulo operation on numbers, the ``%`` operator is |
| 855 | also overloaded by string and unicode objects to perform string formatting (also |
| 856 | known as interpolation). The syntax for string formatting is described in the |
| 857 | Python Library Reference, section :ref:`string-formatting`. |
| 858 | |
| 859 | The floor division operator, the modulo operator, and the :func:`divmod` |
| 860 | function are not defined for complex numbers. Instead, convert to a |
| 861 | floating point number using the :func:`abs` function if appropriate. |
| 862 | |
| 863 | .. index:: single: addition |
| 864 | |
| 865 | The ``+`` (addition) operator yields the sum of its arguments. The arguments |
| 866 | must either both be numbers or both sequences of the same type. In the former |
| 867 | case, the numbers are converted to a common type and then added together. In |
| 868 | the latter case, the sequences are concatenated. |
| 869 | |
| 870 | .. index:: single: subtraction |
| 871 | |
| 872 | The ``-`` (subtraction) operator yields the difference of its arguments. The |
| 873 | numeric arguments are first converted to a common type. |
| 874 | |
| 875 | |
| 876 | .. _shifting: |
| 877 | |
| 878 | Shifting operations |
| 879 | =================== |
| 880 | |
| 881 | .. index:: pair: shifting; operation |
| 882 | |
| 883 | The shifting operations have lower priority than the arithmetic operations: |
| 884 | |
| 885 | .. productionlist:: |
| 886 | shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr` |
| 887 | |
| 888 | These operators accept plain or long integers as arguments. The arguments are |
| 889 | converted to a common type. They shift the first argument to the left or right |
| 890 | by the number of bits given by the second argument. |
| 891 | |
| 892 | .. index:: exception: ValueError |
| 893 | |
| 894 | A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift |
| 895 | by *n* bits is defined as multiplication with ``pow(2,n)``; for plain integers |
| 896 | there is no overflow check so in that case the operation drops bits and flips |
| 897 | the sign if the result is not less than ``pow(2,31)`` in absolute value. |
| 898 | Negative shift counts raise a :exc:`ValueError` exception. |
| 899 | |
| 900 | |
| 901 | .. _bitwise: |
| 902 | |
| 903 | Binary bit-wise operations |
| 904 | ========================== |
| 905 | |
| 906 | .. index:: triple: binary; bit-wise; operation |
| 907 | |
| 908 | Each of the three bitwise operations has a different priority level: |
| 909 | |
| 910 | .. productionlist:: |
| 911 | and_expr: `shift_expr` | `and_expr` "&" `shift_expr` |
| 912 | xor_expr: `and_expr` | `xor_expr` "^" `and_expr` |
| 913 | or_expr: `xor_expr` | `or_expr` "|" `xor_expr` |
| 914 | |
| 915 | .. index:: pair: bit-wise; and |
| 916 | |
| 917 | The ``&`` operator yields the bitwise AND of its arguments, which must be plain |
| 918 | or long integers. The arguments are converted to a common type. |
| 919 | |
| 920 | .. index:: |
| 921 | pair: bit-wise; xor |
| 922 | pair: exclusive; or |
| 923 | |
| 924 | The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which |
| 925 | must be plain or long integers. The arguments are converted to a common type. |
| 926 | |
| 927 | .. index:: |
| 928 | pair: bit-wise; or |
| 929 | pair: inclusive; or |
| 930 | |
| 931 | The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which |
| 932 | must be plain or long integers. The arguments are converted to a common type. |
| 933 | |
| 934 | |
| 935 | .. _comparisons: |
| 936 | |
| 937 | Comparisons |
| 938 | =========== |
| 939 | |
| 940 | .. index:: single: comparison |
| 941 | |
| 942 | .. index:: pair: C; language |
| 943 | |
| 944 | Unlike C, all comparison operations in Python have the same priority, which is |
| 945 | lower than that of any arithmetic, shifting or bitwise operation. Also unlike |
| 946 | C, expressions like ``a < b < c`` have the interpretation that is conventional |
| 947 | in mathematics: |
| 948 | |
| 949 | .. productionlist:: |
| 950 | comparison: `or_expr` ( `comp_operator` `or_expr` )* |
| 951 | comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!=" |
| 952 | : | "is" ["not"] | ["not"] "in" |
| 953 | |
| 954 | Comparisons yield boolean values: ``True`` or ``False``. |
| 955 | |
| 956 | .. index:: pair: chaining; comparisons |
| 957 | |
| 958 | Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to |
| 959 | ``x < y and y <= z``, except that ``y`` is evaluated only once (but in both |
| 960 | cases ``z`` is not evaluated at all when ``x < y`` is found to be false). |
| 961 | |
| 962 | Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *opa*, *opb*, ..., |
| 963 | *opy* are comparison operators, then *a opa b opb c* ...*y opy z* is equivalent |
| 964 | to *a opa b* :keyword:`and` *b opb c* :keyword:`and` ... *y opy z*, except that |
| 965 | each expression is evaluated at most once. |
| 966 | |
| 967 | Note that *a opa b opb c* doesn't imply any kind of comparison between *a* and |
| 968 | *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not |
| 969 | pretty). |
| 970 | |
| 971 | The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the |
| 972 | values of two objects. The objects need not have the same type. If both are |
| 973 | numbers, they are converted to a common type. Otherwise, objects of different |
| 974 | types *always* compare unequal, and are ordered consistently but arbitrarily. |
| 975 | You can control comparison behavior of objects of non-builtin types by defining |
| 976 | a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in |
| 977 | section :ref:`specialnames`. |
| 978 | |
| 979 | (This unusual definition of comparison was used to simplify the definition of |
| 980 | operations like sorting and the :keyword:`in` and :keyword:`not in` operators. |
| 981 | In the future, the comparison rules for objects of different types are likely to |
| 982 | change.) |
| 983 | |
| 984 | Comparison of objects of the same type depends on the type: |
| 985 | |
| 986 | * Numbers are compared arithmetically. |
| 987 | |
| 988 | * Strings are compared lexicographically using the numeric equivalents (the |
| 989 | result of the built-in function :func:`ord`) of their characters. Unicode and |
Guido van Rossum | da27fd2 | 2007-08-17 00:24:54 +0000 | [diff] [blame^] | 990 | 8-bit strings are fully interoperable in this behavior. [#]_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 991 | |
| 992 | * Tuples and lists are compared lexicographically using comparison of |
| 993 | corresponding elements. This means that to compare equal, each element must |
| 994 | compare equal and the two sequences must be of the same type and have the same |
| 995 | length. |
| 996 | |
| 997 | If not equal, the sequences are ordered the same as their first differing |
| 998 | elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as |
| 999 | ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence |
| 1000 | is ordered first (for example, ``[1,2] < [1,2,3]``). |
| 1001 | |
| 1002 | * Mappings (dictionaries) compare equal if and only if their sorted (key, value) |
| 1003 | lists compare equal. [#]_ Outcomes other than equality are resolved |
| 1004 | consistently, but are not otherwise defined. [#]_ |
| 1005 | |
| 1006 | * Most other objects of builtin types compare unequal unless they are the same |
| 1007 | object; the choice whether one object is considered smaller or larger than |
| 1008 | another one is made arbitrarily but consistently within one execution of a |
| 1009 | program. |
| 1010 | |
| 1011 | The operators :keyword:`in` and :keyword:`not in` test for set membership. ``x |
| 1012 | in s`` evaluates to true if *x* is a member of the set *s*, and false otherwise. |
| 1013 | ``x not in s`` returns the negation of ``x in s``. The set membership test has |
| 1014 | traditionally been bound to sequences; an object is a member of a set if the set |
| 1015 | is a sequence and contains an element equal to that object. However, it is |
| 1016 | possible for an object to support membership tests without being a sequence. In |
| 1017 | particular, dictionaries support membership testing as a nicer way of spelling |
| 1018 | ``key in dict``; other mapping types may follow suit. |
| 1019 | |
| 1020 | For the list and tuple types, ``x in y`` is true if and only if there exists an |
| 1021 | index *i* such that ``x == y[i]`` is true. |
| 1022 | |
| 1023 | For the Unicode and string types, ``x in y`` is true if and only if *x* is a |
| 1024 | substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y* |
| 1025 | need not be the same type; consequently, ``u'ab' in 'abc'`` will return |
| 1026 | ``True``. Empty strings are always considered to be a substring of any other |
| 1027 | string, so ``"" in "abc"`` will return ``True``. |
| 1028 | |
| 1029 | .. versionchanged:: 2.3 |
| 1030 | Previously, *x* was required to be a string of length ``1``. |
| 1031 | |
| 1032 | For user-defined classes which define the :meth:`__contains__` method, ``x in |
| 1033 | y`` is true if and only if ``y.__contains__(x)`` is true. |
| 1034 | |
| 1035 | For user-defined classes which do not define :meth:`__contains__` and do define |
| 1036 | :meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative |
| 1037 | integer index *i* such that ``x == y[i]``, and all lower integer indices do not |
| 1038 | raise :exc:`IndexError` exception. (If any other exception is raised, it is as |
| 1039 | if :keyword:`in` raised that exception). |
| 1040 | |
| 1041 | .. index:: |
| 1042 | operator: in |
| 1043 | operator: not in |
| 1044 | pair: membership; test |
| 1045 | object: sequence |
| 1046 | |
| 1047 | The operator :keyword:`not in` is defined to have the inverse true value of |
| 1048 | :keyword:`in`. |
| 1049 | |
| 1050 | .. index:: |
| 1051 | operator: is |
| 1052 | operator: is not |
| 1053 | pair: identity; test |
| 1054 | |
| 1055 | The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x |
| 1056 | is y`` is true if and only if *x* and *y* are the same object. ``x is not y`` |
| 1057 | yields the inverse truth value. |
| 1058 | |
| 1059 | |
| 1060 | .. _booleans: |
| 1061 | |
| 1062 | Boolean operations |
| 1063 | ================== |
| 1064 | |
| 1065 | .. index:: |
| 1066 | pair: Conditional; expression |
| 1067 | pair: Boolean; operation |
| 1068 | |
| 1069 | Boolean operations have the lowest priority of all Python operations: |
| 1070 | |
| 1071 | .. productionlist:: |
| 1072 | expression: `conditional_expression` | `lambda_form` |
| 1073 | old_expression: `or_test` | `old_lambda_form` |
| 1074 | conditional_expression: `or_test` ["if" `or_test` "else" `expression`] |
| 1075 | or_test: `and_test` | `or_test` "or" `and_test` |
| 1076 | and_test: `not_test` | `and_test` "and" `not_test` |
| 1077 | not_test: `comparison` | "not" `not_test` |
| 1078 | |
| 1079 | In the context of Boolean operations, and also when expressions are used by |
| 1080 | control flow statements, the following values are interpreted as false: |
| 1081 | ``False``, ``None``, numeric zero of all types, and empty strings and containers |
| 1082 | (including strings, tuples, lists, dictionaries, sets and frozensets). All |
| 1083 | other values are interpreted as true. |
| 1084 | |
| 1085 | .. index:: operator: not |
| 1086 | |
| 1087 | The operator :keyword:`not` yields ``True`` if its argument is false, ``False`` |
| 1088 | otherwise. |
| 1089 | |
| 1090 | The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is |
| 1091 | true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated |
| 1092 | and its value is returned. |
| 1093 | |
| 1094 | .. versionadded:: 2.5 |
| 1095 | |
| 1096 | .. index:: operator: and |
| 1097 | |
| 1098 | The expression ``x and y`` first evaluates *x*; if *x* is false, its value is |
| 1099 | returned; otherwise, *y* is evaluated and the resulting value is returned. |
| 1100 | |
| 1101 | .. index:: operator: or |
| 1102 | |
| 1103 | The expression ``x or y`` first evaluates *x*; if *x* is true, its value is |
| 1104 | returned; otherwise, *y* is evaluated and the resulting value is returned. |
| 1105 | |
| 1106 | (Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type |
| 1107 | they return to ``False`` and ``True``, but rather return the last evaluated |
| 1108 | argument. This is sometimes useful, e.g., if ``s`` is a string that should be |
| 1109 | replaced by a default value if it is empty, the expression ``s or 'foo'`` yields |
| 1110 | the desired value. Because :keyword:`not` has to invent a value anyway, it does |
| 1111 | not bother to return a value of the same type as its argument, so e.g., ``not |
| 1112 | 'foo'`` yields ``False``, not ``''``.) |
| 1113 | |
| 1114 | |
| 1115 | .. _lambdas: |
| 1116 | |
| 1117 | Lambdas |
| 1118 | ======= |
| 1119 | |
| 1120 | .. index:: |
| 1121 | pair: lambda; expression |
| 1122 | pair: lambda; form |
| 1123 | pair: anonymous; function |
| 1124 | |
| 1125 | .. productionlist:: |
| 1126 | lambda_form: "lambda" [`parameter_list`]: `expression` |
| 1127 | old_lambda_form: "lambda" [`parameter_list`]: `old_expression` |
| 1128 | |
| 1129 | Lambda forms (lambda expressions) have the same syntactic position as |
| 1130 | expressions. They are a shorthand to create anonymous functions; the expression |
| 1131 | ``lambda arguments: expression`` yields a function object. The unnamed object |
| 1132 | behaves like a function object defined with :: |
| 1133 | |
| 1134 | def name(arguments): |
| 1135 | return expression |
| 1136 | |
| 1137 | See section :ref:`function` for the syntax of parameter lists. Note that |
| 1138 | functions created with lambda forms cannot contain statements or annotations. |
| 1139 | |
| 1140 | .. _lambda: |
| 1141 | |
| 1142 | |
| 1143 | .. _exprlists: |
| 1144 | |
| 1145 | Expression lists |
| 1146 | ================ |
| 1147 | |
| 1148 | .. index:: pair: expression; list |
| 1149 | |
| 1150 | .. productionlist:: |
| 1151 | expression_list: `expression` ( "," `expression` )* [","] |
| 1152 | |
| 1153 | .. index:: object: tuple |
| 1154 | |
| 1155 | An expression list containing at least one comma yields a tuple. The length of |
| 1156 | the tuple is the number of expressions in the list. The expressions are |
| 1157 | evaluated from left to right. |
| 1158 | |
| 1159 | .. index:: pair: trailing; comma |
| 1160 | |
| 1161 | The trailing comma is required only to create a single tuple (a.k.a. a |
| 1162 | *singleton*); it is optional in all other cases. A single expression without a |
| 1163 | trailing comma doesn't create a tuple, but rather yields the value of that |
| 1164 | expression. (To create an empty tuple, use an empty pair of parentheses: |
| 1165 | ``()``.) |
| 1166 | |
| 1167 | |
| 1168 | .. _evalorder: |
| 1169 | |
| 1170 | Evaluation order |
| 1171 | ================ |
| 1172 | |
| 1173 | .. index:: pair: evaluation; order |
| 1174 | |
| 1175 | Python evaluates expressions from left to right. Notice that while evaluating an |
| 1176 | assignment, the right-hand side is evaluated before the left-hand side. |
| 1177 | |
| 1178 | In the following lines, expressions will be evaluated in the arithmetic order of |
| 1179 | their suffixes:: |
| 1180 | |
| 1181 | expr1, expr2, expr3, expr4 |
| 1182 | (expr1, expr2, expr3, expr4) |
| 1183 | {expr1: expr2, expr3: expr4} |
| 1184 | expr1 + expr2 * (expr3 - expr4) |
| 1185 | func(expr1, expr2, *expr3, **expr4) |
| 1186 | expr3, expr4 = expr1, expr2 |
| 1187 | |
| 1188 | |
| 1189 | .. _operator-summary: |
| 1190 | |
| 1191 | Summary |
| 1192 | ======= |
| 1193 | |
| 1194 | .. index:: pair: operator; precedence |
| 1195 | |
| 1196 | The following table summarizes the operator precedences in Python, from lowest |
| 1197 | precedence (least binding) to highest precedence (most binding). Operators in |
| 1198 | the same box have the same precedence. Unless the syntax is explicitly given, |
| 1199 | operators are binary. Operators in the same box group left to right (except for |
| 1200 | comparisons, including tests, which all have the same precedence and chain from |
| 1201 | left to right --- see section :ref:`comparisons` --- and exponentiation, which |
| 1202 | groups from right to left). |
| 1203 | |
| 1204 | +----------------------------------------------+-------------------------------------+ |
| 1205 | | Operator | Description | |
| 1206 | +==============================================+=====================================+ |
| 1207 | | :keyword:`lambda` | Lambda expression | |
| 1208 | +----------------------------------------------+-------------------------------------+ |
| 1209 | | :keyword:`or` | Boolean OR | |
| 1210 | +----------------------------------------------+-------------------------------------+ |
| 1211 | | :keyword:`and` | Boolean AND | |
| 1212 | +----------------------------------------------+-------------------------------------+ |
| 1213 | | :keyword:`not` *x* | Boolean NOT | |
| 1214 | +----------------------------------------------+-------------------------------------+ |
| 1215 | | :keyword:`in`, :keyword:`not` :keyword:`in` | Membership tests | |
| 1216 | +----------------------------------------------+-------------------------------------+ |
| 1217 | | :keyword:`is`, :keyword:`is not` | Identity tests | |
| 1218 | +----------------------------------------------+-------------------------------------+ |
| 1219 | | ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==`` | Comparisons | |
| 1220 | +----------------------------------------------+-------------------------------------+ |
| 1221 | | ``|`` | Bitwise OR | |
| 1222 | +----------------------------------------------+-------------------------------------+ |
| 1223 | | ``^`` | Bitwise XOR | |
| 1224 | +----------------------------------------------+-------------------------------------+ |
| 1225 | | ``&`` | Bitwise AND | |
| 1226 | +----------------------------------------------+-------------------------------------+ |
| 1227 | | ``<<``, ``>>`` | Shifts | |
| 1228 | +----------------------------------------------+-------------------------------------+ |
| 1229 | | ``+``, ``-`` | Addition and subtraction | |
| 1230 | +----------------------------------------------+-------------------------------------+ |
| 1231 | | ``*``, ``/``, ``%`` | Multiplication, division, remainder | |
| 1232 | +----------------------------------------------+-------------------------------------+ |
| 1233 | | ``+x``, ``-x`` | Positive, negative | |
| 1234 | +----------------------------------------------+-------------------------------------+ |
| 1235 | | ``~x`` | Bitwise not | |
| 1236 | +----------------------------------------------+-------------------------------------+ |
| 1237 | | ``**`` | Exponentiation | |
| 1238 | +----------------------------------------------+-------------------------------------+ |
| 1239 | | ``x.attribute`` | Attribute reference | |
| 1240 | +----------------------------------------------+-------------------------------------+ |
| 1241 | | ``x[index]`` | Subscription | |
| 1242 | +----------------------------------------------+-------------------------------------+ |
| 1243 | | ``x[index:index]`` | Slicing | |
| 1244 | +----------------------------------------------+-------------------------------------+ |
| 1245 | | ``f(arguments...)`` | Function call | |
| 1246 | +----------------------------------------------+-------------------------------------+ |
| 1247 | | ``(expressions...)`` | Binding or tuple display | |
| 1248 | +----------------------------------------------+-------------------------------------+ |
| 1249 | | ``[expressions...]`` | List display | |
| 1250 | +----------------------------------------------+-------------------------------------+ |
| 1251 | | ``{key:datum...}`` | Dictionary display | |
| 1252 | +----------------------------------------------+-------------------------------------+ |
| 1253 | |
| 1254 | .. rubric:: Footnotes |
| 1255 | |
| 1256 | .. [#] In Python 2.3, a list comprehension "leaks" the control variables of each |
| 1257 | ``for`` it contains into the containing scope. However, this behavior is |
| 1258 | deprecated, and relying on it will not work once this bug is fixed in a future |
| 1259 | release |
| 1260 | |
| 1261 | .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be |
| 1262 | true numerically due to roundoff. For example, and assuming a platform on which |
| 1263 | a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % |
| 1264 | 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 + |
| 1265 | 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod` |
| 1266 | in the :mod:`math` module returns a result whose sign matches the sign of the |
| 1267 | first argument instead, and so returns ``-1e-100`` in this case. Which approach |
| 1268 | is more appropriate depends on the application. |
| 1269 | |
| 1270 | .. [#] If x is very close to an exact integer multiple of y, it's possible for |
| 1271 | ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such |
| 1272 | cases, Python returns the latter result, in order to preserve that |
| 1273 | ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. |
| 1274 | |
Guido van Rossum | da27fd2 | 2007-08-17 00:24:54 +0000 | [diff] [blame^] | 1275 | .. [#] While comparisons between unicode strings make sense at the byte |
| 1276 | level, they may be counter-intuitive to users. For example, the |
| 1277 | strings ``u"\u00C7"`` and ``u"\u0327\u0043"`` compare differently, |
| 1278 | even though they both represent the same unicode character (LATIN |
| 1279 | CAPTITAL LETTER C WITH CEDILLA). |
| 1280 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1281 | .. [#] The implementation computes this efficiently, without constructing lists or |
| 1282 | sorting. |
| 1283 | |
| 1284 | .. [#] Earlier versions of Python used lexicographic comparison of the sorted (key, |
| 1285 | value) lists, but this was very expensive for the common case of comparing for |
| 1286 | equality. An even earlier version of Python compared dictionaries by identity |
| 1287 | only, but this caused surprises because people expected to be able to test a |
| 1288 | dictionary for emptiness by comparing it to ``{}``. |
| 1289 | |