Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(230)

Delta Between Two Patch Sets: Doc/reference/expressions.rst

Issue 11682: PEP 380 reference implementation for 3.3
Left Patch Set: Created 7 years, 8 months ago
Right Patch Set: Created 7 years, 4 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Doc/library/exceptions.rst ('k') | Doc/reference/simple_stmts.rst » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 1
2 .. _expressions: 2 .. _expressions:
3 3
4 *********** 4 ***********
5 Expressions 5 Expressions
6 *********** 6 ***********
7 7
8 .. index:: expression, BNF 8 .. index:: expression, BNF
9 9
10 This chapter explains the meaning of the elements of expressions in Python. 10 This chapter explains the meaning of the elements of expressions in Python.
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
49 49
50 .. index:: atom 50 .. index:: atom
51 51
52 Atoms are the most basic elements of expressions. The simplest atoms are 52 Atoms are the most basic elements of expressions. The simplest atoms are
53 identifiers or literals. Forms enclosed in parentheses, brackets or braces are 53 identifiers or literals. Forms enclosed in parentheses, brackets or braces are
54 also categorized syntactically as atoms. The syntax for atoms is: 54 also categorized syntactically as atoms. The syntax for atoms is:
55 55
56 .. productionlist:: 56 .. productionlist::
57 atom: `identifier` | `literal` | `enclosure` 57 atom: `identifier` | `literal` | `enclosure`
58 enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display` 58 enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display`
59 : | `generator_expression` | `yield_expression` 59 : | `generator_expression` | `yield_atom`
60 60
61 61
62 .. _atom-identifiers: 62 .. _atom-identifiers:
63 63
64 Identifiers (Names) 64 Identifiers (Names)
65 ------------------- 65 -------------------
66 66
67 .. index:: name, identifier 67 .. index:: name, identifier
68 68
69 An identifier occurring as an atom is a name. See section :ref:`identifiers` 69 An identifier occurring as an atom is a name. See section :ref:`identifiers`
(...skipping 240 matching lines...) Expand 10 before | Expand all | Expand 10 after
310 310
311 Yield expressions 311 Yield expressions
312 ----------------- 312 -----------------
313 313
314 .. index:: 314 .. index::
315 keyword: yield 315 keyword: yield
316 pair: yield; expression 316 pair: yield; expression
317 pair: generator; function 317 pair: generator; function
318 318
319 .. productionlist:: 319 .. productionlist::
320 yield_expression: "(" `yield_stmt` ")" 320 yield_atom: "(" `yield_expression` ")"
321 321 yield_expression: "yield" [`expression_list` | "from" `expression`]
322 The :keyword:`yield` statement appears only in generator functions and is used 322
323 to pause the execution of a function and pass a value to the caller. The 323 The :keyword:`yield` expression is only used when defining a generator function,
eric.araujo 2011/09/21 16:25:47 This file uses two spaces after dots, please do th
324 behaviour of :keyword:`yield` depends on the generator method that was called 324 and can only be used in the body of a function definition. Using a
325 and is described in detail `elsewhere <yield>`_. Here, only the behaviour of 325 :keyword:`yield` expression in a function definition is sufficient to cause that
326 :keyword:`yield` as an expression is documented. 326 definition to create a generator function instead of a normal function.
327 327
328 When :token:`yield from <yield_from>` is used, the :attr:`~StopIteration.value` 328 When a generator function is called, it returns an iterator known as a
329 attribute of :exc:`StopIteration` used to signal the exhaustion of the 329 generator. That generator then controls the execution of a generator function.
330 sub-generator becomes the value of the yield expression. It can be either set 330 The execution starts when one of the generator's methods is called. At that
331 explicitely when raising :exc:`StopIteration`, or automatically when the 331 time, the execution proceeds to the first :keyword:`yield` expression, where it
332 sub-generator is a generator, by returning a value from the sub-generator 332 is suspended again, returning the value of :token:`expression_list` to
333 function. 333 generator's caller. By suspended we mean that all local state is retained,
334 334 including the current bindings of local variables, the instruction pointer, and
335 When a :token:`normal yield <yield_arg>` is used, the value of the 335 the internal evaluation stack. When the execution is resumed by calling one of
336 :token:`yield_expression` depends on the generator method that was called. When 336 the generator's methods, the function can proceed exactly as if the
337 the generator's :obj:`~generator.__next__` method is used, the value of the 337 :keyword:`yield` expression was just another external call. The value of the
338 yield expression is :const:`None`, this is the most common case. When the 338 :keyword:`yield` expression after resuming depends on the method which resumed
339 generator's :obj:`send(value) <generator.send>` method is used, the ``value`` 339 the execution. If :meth:`__next__` is used (typically via either a
eric.araujo 2011/09/21 16:25:47 I’d say :meth:`~generator.send`
340 passed as an argument becomes the value of the :token:`yield_expression`. 340 :keyword:`for` or the :func:`next` builtin) then the result is :const:`None`,
341 341 otherwise, if :meth:`send` is used, then the result will be the value passed
342 The other two generator methods cause an exception to be raised at the point of 342 in to that method.
343 the yield statement. :meth:`~generator.throw` takes exception details as 343
344 arguments and is used to raise an arbitrary expression at the point where the 344 .. index:: single: coroutine
345 generator function is stopped after :keyword:`yield`. :meth:`~generator.close` 345
346 is used to finalize generators and causes a :exc:`GeneratorExit` exception to be 346 All of this makes generator functions quite similar to coroutines; they yield
347 raised at the point of the :keyword:`yield` statement. 347 multiple times, they have more than one entry point and their execution can be
348 348 suspended. The only difference is that a generator function cannot control
349 The parentheses can be ommited when the :token:`yield statement <yield_stmt>` 349 where should the execution continue after it yields; the control is always
350 occurs in a top-level expression on the right-hand side of an assignment. 350 transferred to the generator's caller.
351
352 :keyword:`yield` expressions are allowed in the :keyword:`try` clause of a
353 :keyword:`try` ... :keyword:`finally` construct. If the generator is not
354 resumed before it is finalized (by reaching a zero reference count or by being
355 garbage collected), the generator-iterator's :meth:`close` method will be
356 called, allowing any pending :keyword:`finally` clauses to execute.
357
358 When ``yield from expression`` is used, it treats the supplied expression as
359 a subiterator. All values produced by that subiterator are passed directly
360 to the caller of the current generator's methods. Any values passed in with
361 :meth:`send` and any exceptions passed in with :meth:`throw` are passed to
362 the underlying iterator if it has the appropriate methods. If this is not the
363 case, then :meth:`send` will raise :exc:`AttributeError` or :exc:`TypeError`,
364 while :meth:`throw` will just raise the passed in exception immediately.
365
366 When the underlying iterator is complete, the :attr:`~StopIteration.value`
367 attribute of the raised :exc:`StopIteration` instance becomes the value of
368 the yield expression. It can be either set explicitly when raising
369 :exc:`StopIteration`, or automatically when the sub-iterator is a generator
370 (by returning a value from the sub-generator).
371
372 The parentheses can be omitted when the :keyword:`yield` expression is the
373 sole expression on the right hand side of an assignment statement.
374
375 .. index:: object: generator
376
377 The following generator's methods can be used to control the execution of a
378 generator function:
379
380 .. index:: exception: StopIteration
381
382
383 .. method:: generator.__next__()
384
385 Starts the execution of a generator function or resumes it at the last
386 executed :keyword:`yield` expression. When a generator function is resumed
387 with a :meth:`__next__` method, the current :keyword:`yield` expression
388 always evaluates to :const:`None`. The execution then continues to the next
389 :keyword:`yield` expression, where the generator is suspended again, and the
390 value of the :token:`expression_list` is returned to :meth:`next`'s caller.
391 If the generator exits without yielding another value, a :exc:`StopIteration`
392 exception is raised.
393
394 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
395 by the built-in :func:`next` function.
396
397
398 .. method:: generator.send(value)
399
400 Resumes the execution and "sends" a value into the generator function. The
401 ``value`` argument becomes the result of the current :keyword:`yield`
402 expression. The :meth:`send` method returns the next value yielded by the
403 generator, or raises :exc:`StopIteration` if the generator exits without
404 yielding another value. When :meth:`send` is called to start the generator,
405 it must be called with :const:`None` as the argument, because there is no
406 :keyword:`yield` expression that could receive the value.
407
408
409 .. method:: generator.throw(type[, value[, traceback]])
410
411 Raises an exception of type ``type`` at the point where generator was paused,
412 and returns the next value yielded by the generator function. If the generat or
413 exits without yielding another value, a :exc:`StopIteration` exception is
414 raised. If the generator function does not catch the passed-in exception, or
415 raises a different exception, then that exception propagates to the caller.
416
417 .. index:: exception: GeneratorExit
418
419
420 .. method:: generator.close()
421
422 Raises a :exc:`GeneratorExit` at the point where the generator function was
423 paused. If the generator function then raises :exc:`StopIteration` (by
424 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
425 not catching the exception), close returns to its caller. If the generator
426 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
427 other exception, it is propagated to the caller. :meth:`close` does nothing
428 if the generator has already exited due to an exception or normal exit.
429
430 Here is a simple example that demonstrates the behavior of generators and
431 generator functions::
432
433 >>> def echo(value=None):
434 ... print("Execution starts when 'next()' is called for the first time.")
435 ... try:
436 ... while True:
437 ... try:
438 ... value = (yield value)
439 ... except Exception as e:
440 ... value = e
441 ... finally:
442 ... print("Don't forget to clean up when 'close()' is called.")
443 ...
444 >>> generator = echo(1)
445 >>> print(next(generator))
446 Execution starts when 'next()' is called for the first time.
447 1
448 >>> print(next(generator))
449 None
450 >>> print(generator.send(2))
451 2
452 >>> generator.throw(TypeError, "spam")
453 TypeError('spam',)
454 >>> generator.close()
455 Don't forget to clean up when 'close()' is called.
456
351 457
352 .. seealso:: 458 .. seealso::
353 459
354 The documentation for the :keyword:`yield` statement. 460 :pep:`0255` - Simple Generators
eric.araujo 2011/09/21 16:25:47 I’d remove the seealso section entirely; your doc
461 The proposal for adding generators and the :keyword:`yield` statement to P ython.
462
463 :pep:`0342` - Coroutines via Enhanced Generators
464 The proposal to enhance the API and syntax of generators, making them
465 usable as simple coroutines.
466
467 :pep:`0380` - Syntax for Delegating to a Subgenerator
468 The proposal to introduce the :token:`yield_from` syntax, making delegatio n
469 to sub-generators easy.
470
355 471
356 .. _primaries: 472 .. _primaries:
357 473
358 Primaries 474 Primaries
359 ========= 475 =========
360 476
361 .. index:: single: primary 477 .. index:: single: primary
362 478
363 Primaries represent the most tightly bound operations of the language. Their 479 Primaries represent the most tightly bound operations of the language. Their
364 syntax is: 480 syntax is:
(...skipping 891 matching lines...) Expand 10 before | Expand all | Expand 10 after
1256 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature o f 1372 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature o f
1257 descriptors, you may notice seemingly unusual behaviour in certain uses of 1373 descriptors, you may notice seemingly unusual behaviour in certain uses of
1258 the :keyword:`is` operator, like those involving comparisons between instance 1374 the :keyword:`is` operator, like those involving comparisons between instance
1259 methods, or constants. Check their documentation for more info. 1375 methods, or constants. Check their documentation for more info.
1260 1376
1261 .. [#] The ``%`` operator is also used for string formatting; the same 1377 .. [#] The ``%`` operator is also used for string formatting; the same
1262 precedence applies. 1378 precedence applies.
1263 1379
1264 .. [#] The power operator ``**`` binds less tightly than an arithmetic or 1380 .. [#] The power operator ``**`` binds less tightly than an arithmetic or
1265 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. 1381 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+