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