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