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

Side by Side Diff: Doc/reference/simple_stmts.rst

Issue 11682: PEP 380 reference implementation for 3.3
Patch Set: Created 8 years 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:
View unified diff | Download patch
« Doc/reference/expressions.rst ('K') | « Doc/reference/expressions.rst ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 1
2 .. _simple: 2 .. _simple:
3 3
4 ***************** 4 *****************
5 Simple statements 5 Simple statements
6 ***************** 6 *****************
7 7
8 .. index:: pair: simple; statement 8 .. index:: pair: simple; statement
9 9
10 Simple statements are comprised within a single logical line. Several simple 10 Simple statements are comprised within a single logical line. Several simple
(...skipping 407 matching lines...) Expand 10 before | Expand all | Expand 10 after
418 418
419 :keyword:`return` leaves the current function call with the expression list (or 419 :keyword:`return` leaves the current function call with the expression list (or
420 ``None``) as return value. 420 ``None``) as return value.
421 421
422 .. index:: keyword: finally 422 .. index:: keyword: finally
423 423
424 When :keyword:`return` passes control out of a :keyword:`try` statement with a 424 When :keyword:`return` passes control out of a :keyword:`try` statement with a
425 :keyword:`finally` clause, that :keyword:`finally` clause is executed before 425 :keyword:`finally` clause, that :keyword:`finally` clause is executed before
426 really leaving the function. 426 really leaving the function.
427 427
428 In a generator function, the :keyword:`return` statement is not allowed to 428 In a generator function, the :keyword:`return` statement indicates that the
429 include an :token:`expression_list`. In that context, a bare :keyword:`return` 429 generator is done and will cause :exc:`StopIteration` to be raised. The returned
430 indicates that the generator is done and will cause :exc:`StopIteration` to be 430 value is used as an argument to construct :exc:`StopIteration` and becomes the
431 raised. 431 :attr:`StopIteration.value` attribute.
eric.araujo 2011/09/21 16:25:47 The returned value is used as argument to :exc:`St
432 432
433 433
434 .. _yield: 434 .. _yield:
435 435
436 The :keyword:`yield` statement 436 The :keyword:`yield` statement
437 ============================== 437 ==============================
438 438
439 .. index:: 439 .. index::
440 statement: yield 440 statement: yield
441 single: generator; function 441 single: generator; function
442 single: generator; iterator 442 single: generator; iterator
443 single: function; generator 443 single: function; generator
444 exception: StopIteration 444 exception: StopIteration
445 445
446 .. productionlist:: 446 .. productionlist::
447 yield_stmt: `yield_expression` 447 yield_stmt: `yield_arg` | `yield_from`
448 yield_arg: "yield" [`expression_list`]
449 yield_from: "yield" "from" [`expression_list`]
448 450
449 The :keyword:`yield` statement is only used when defining a generator function, 451 The :keyword:`yield` expression is only used when defining a generator function,
450 and is only used in the body of the generator function. Using a :keyword:`yield` 452 and can only be used in the body of a function definition. Using a
451 statement in a function definition is sufficient to cause that definition to 453 :keyword:`yield` expression in a function definition is sufficient to cause that
452 create a generator function instead of a normal function. 454 definition to create a generator function instead of a normal function.
455
453 When a generator function is called, it returns an iterator known as a generator 456 When a generator function is called, it returns an iterator known as a generator
454 iterator, or more commonly, a generator. The body of the generator function is 457 iterator, or more commonly, a generator. That generator then controls the
eric.araujo 2011/09/21 16:25:47 I’d remove the second comma.
455 executed by calling the :func:`next` function on the generator repeatedly until 458 execution of the generator function. The execution starts when one of the
456 it raises an exception. 459 generator's methods is called. At that time, the execution proceeds to the first
460 :keyword:`yield` expression. What happens next depends on whether the simpler
461 :token:`yield_arg` or the more complicated :token:`yield_from` form was used.
457 462
458 When a :keyword:`yield` statement is executed, the state of the generator is 463 In the first case, when ``from`` is not used, the execution of the generator
459 frozen and the value of :token:`expression_list` is returned to :meth:`next`'s 464 function is suspended again, returning the value of :token:`expression_list` to
460 caller. By "frozen" we mean that all local state is retained, including the 465 generator's caller. By suspended we mean that all local state is retained,
461 current bindings of local variables, the instruction pointer, and the internal 466 including the current bindings of local variables, the instruction pointer, and
462 evaluation stack: enough information is saved so that the next time :func:`next` 467 the internal evaluation stack. When the execution is resumed by calling one of
463 is invoked, the function can proceed exactly as if the :keyword:`yield` 468 the generator's methods, the function can proceed exactly as if the
464 statement were just another external call. 469 :keyword:`yield` expression was just another external call. The value of the
470 :keyword:`yield` expression after resuming depends on the method which resumed
471 the execution.
465 472
466 The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a 473 In the second case, when ``from`` is used, the :token:`expression_list` is
467 :keyword:`try` ... :keyword:`finally` construct. If the generator is not 474 expected to yield an iterator, a "sub-generator". The evaluation of the
eric.araujo 2011/09/21 16:25:47 I think that using “yield” here may be confusing.
468 resumed before it is finalized (by reaching a zero reference count or by being 475 generator is then delegated to this sub-generator. This means that the generator
469 garbage collected), the generator-iterator's :meth:`close` method will be 476 function is suspended like in the first case, but calls to
470 called, allowing any pending :keyword:`finally` clauses to execute. 477 :meth:`~generator.__next__`, :meth:`~generator.send`, :meth:`~generator.throw`,
478 and :meth:`~generator.close` are propagated to the sub-generator until it is
479 exhausted (and raises :exc:`StopIteration`) or until it terminates through an
480 exception (which is then re-raised at the point of the original
481 :token:`yield_from`). This includes the call which causes the original generator
482 function to reach the :token:`yield_from` statement. If :token:`expression_list`
483 yields something that is not an iterator, a :exc:`TypeError` is raised. The
484 behaviour of a :token:`yield_from` expression is similar to repeatedly calling
485 ``return yield`` in a loop, but in contrast also propagates the exceptions and
486 values injected with :meth:`~generator.throw` and :meth:`~generator.send`.
487
488 .. index:: single: coroutine
489
490 All of this makes generator functions quite similar to coroutines; they yield
491 multiple times, they have more than one entry point and their execution can be
492 suspended. The only difference is that a generator function cannot control
493 where should the execution continue after it yields; the control is always
494 transferred to the generator's caller.
495
496 The :keyword:`yield` statement is allowed anywhere in the body of the generator
497 function, also in the :keyword:`try` clause of a :keyword:`try` ...
498 :keyword:`finally` construct. The :keyword:`finally` clause is still guaranteed
499 to be executed before the interpreter terminates. Before the generator is
500 destroyed (after reaching a zero reference count or being garbage collected),
501 the generator-iterator's :meth:`~generator.close` method is called, allowing any
502 pending :keyword:`finally` clauses to execute.
503
504 .. index:: object: generator
505
506 The following generator's methods can be used to control the execution of a
507 generator function:
508
509 .. index:: exception: StopIteration
510
511
512 .. method:: generator.__next__()
513
514 Starts the execution of a generator function or resumes it at the last
515 executed :keyword:`yield` expression. When a generator function is resumed
516 with a :meth:`__next__` method, the current :keyword:`yield` expression
517 always evaluates to :const:`None`. The execution then continues to the next
518 :keyword:`yield` expression, where the generator is suspended again, and the
519 value of the :token:`expression_list` is returned to :meth:`next`'s caller.
520 If the generator exits without yielding another value, a :exc:`StopIteration`
521 exception is raised.
522
523 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
524 by the built-in :func:`next` function.
525
526
527 .. method:: generator.send(value)
528
529 Resumes the execution and "sends" a value into the generator function. The
530 ``value`` argument becomes the result of the current :keyword:`yield`
531 expression. The :meth:`send` method returns the next value yielded by the
532 generator, or raises :exc:`StopIteration` if the generator exits without
533 yielding another value. When :meth:`send` is called to start the generator,
534 it must be called with :const:`None` as the argument, because there is no
535 :keyword:`yield` expression that could receive the value.
536
537
538 .. method:: generator.throw(type[, value[, traceback]])
539
540 Raises an exception of type ``type`` at the point where generator was paused,
541 and returns the next value yielded by the generator function. If the generat or
542 exits without yielding another value, a :exc:`StopIteration` exception is
543 raised. If the generator function does not catch the passed-in exception, or
544 raises a different exception, then that exception propagates to the caller.
545
546 .. index:: exception: GeneratorExit
547
548
549 .. method:: generator.close()
550
551 Raises a :exc:`GeneratorExit` at the point where the generator function was
552 paused. If the generator function then raises :exc:`StopIteration` (by
553 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
554 not catching the exception), close returns to its caller. If the generator
555 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
556 other exception, it is propagated to the caller. :meth:`close` does nothing
557 if the generator has already exited due to an exception or normal exit.
558
559 Here is a simple example that demonstrates the behavior of generators and
560 generator functions::
561
562 >>> def echo(value=None):
563 ... print("Execution starts when 'next()' is called for the first time.")
564 ... try:
565 ... while True:
566 ... try:
567 ... value = yield value
568 ... except Exception as e:
569 ... value = e
570 ... finally:
571 ... print("Don't forget to clean up when 'close()' is called.")
572 ...
573 >>> generator = echo(1)
574 >>> next(generator)
575 Execution starts when 'next()' is called for the first time.
576 1
577 >>> print(next(generator))
578 None
579 >>> generator.send(2)
580 2
581 >>> generator.throw(TypeError, "spam")
582 TypeError('spam',)
583 >>> generator.close()
584 Don't forget to clean up when 'close()' is called.
585
586 When using :token:`yield_from`, work is delegated to the subgenerator::
587
588 >>> def outer():
589 ... print("Outer generator started")
590 ... try:
591 ... yield from echo()
592 ... finally:
593 ... print("Outer generator done")
594 >>> generator = outer()
595 >>> next(generator)
596 Outer generator started
597 Execution starts when 'next()' is called for the first time.
598 >>> generator.send(2)
599 2
600 >>> generator.throw(TypeError, "spam")
601 TypeError('spam',)
602 >>> generator.close()
603 Don't forget to clean up when 'close()' is called.
604 Outer generator done
605 >>> generator.close()
471 606
472 .. seealso:: 607 .. seealso::
473 608
474 :pep:`0255` - Simple Generators 609 :pep:`0255` - Simple Generators
475 The proposal for adding generators and the :keyword:`yield` statement to P ython. 610 The proposal for adding generators and the :keyword:`yield` statement to P ython.
476 611
477 :pep:`0342` - Coroutines via Enhanced Generators 612 :pep:`0342` - Coroutines via Enhanced Generators
478 The proposal that, among other generator enhancements, proposed allowing 613 The proposal to enhance the API and syntax of generators, making them
479 :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block. 614 usable as simple coroutines.
480 615
616 :pep:`0380` - Syntax for Delegating to a Subgenerator
617 The proposal to introduce the :token:`yield_from` syntax, making delegatio n
618 to sub-generators easy.
481 619
482 .. _raise: 620 .. _raise:
483 621
484 The :keyword:`raise` statement 622 The :keyword:`raise` statement
485 ============================== 623 ==============================
486 624
487 .. index:: 625 .. index::
488 statement: raise 626 statement: raise
489 single: exception 627 single: exception
490 pair: raising; exception 628 pair: raising; exception
(...skipping 490 matching lines...) Expand 10 before | Expand all | Expand 10 after
981 enclosing scope (the scope in which a new binding should be created cannot 1119 enclosing scope (the scope in which a new binding should be created cannot
982 be determined unambiguously). 1120 be determined unambiguously).
983 1121
984 Names listed in a :keyword:`nonlocal` statement must not collide with 1122 Names listed in a :keyword:`nonlocal` statement must not collide with
985 pre-existing bindings in the local scope. 1123 pre-existing bindings in the local scope.
986 1124
987 .. seealso:: 1125 .. seealso::
988 1126
989 :pep:`3104` - Access to Names in Outer Scopes 1127 :pep:`3104` - Access to Names in Outer Scopes
990 The specification for the :keyword:`nonlocal` statement. 1128 The specification for the :keyword:`nonlocal` statement.
OLDNEW
« Doc/reference/expressions.rst ('K') | « Doc/reference/expressions.rst ('k') | no next file » | no next file with comments »

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