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

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

Issue 11682: PEP 380 reference implementation for 3.3
Left Patch Set: Created 7 years, 11 months ago
Right Patch Set: Created 7 years, 7 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/reference/expressions.rst ('k') | Doc/whatsnew/3.3.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 .. _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 354 matching lines...) Expand 10 before | Expand all | Expand 10 after
365 365
366 .. index:: 366 .. index::
367 statement: del 367 statement: del
368 pair: deletion; target 368 pair: deletion; target
369 triple: deletion; target; list 369 triple: deletion; target; list
370 370
371 .. productionlist:: 371 .. productionlist::
372 del_stmt: "del" `target_list` 372 del_stmt: "del" `target_list`
373 373
374 Deletion is recursively defined very similar to the way assignment is defined. 374 Deletion is recursively defined very similar to the way assignment is defined.
375 Rather that spelling it out in full details, here are some hints. 375 Rather than spelling it out in full details, here are some hints.
376 376
377 Deletion of a target list recursively deletes each target, from left to right. 377 Deletion of a target list recursively deletes each target, from left to right.
378 378
379 .. index:: 379 .. index::
380 statement: global 380 statement: global
381 pair: unbinding; name 381 pair: unbinding; name
382 382
383 Deletion of a name removes the binding of that name from the local or global 383 Deletion of a name removes the binding of that name from the local or global
384 namespace, depending on whether the name occurs in a :keyword:`global` statement 384 namespace, depending on whether the name occurs in a :keyword:`global` statement
385 in the same code block. If the name is unbound, a :exc:`NameError` exception 385 in the same code block. If the name is unbound, a :exc:`NameError` exception
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
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 indicates that the 428 In a generator function, the :keyword:`return` statement indicates that the
429 generator is done and will cause :exc:`StopIteration` to be raised. The returned 429 generator is done and will cause :exc:`StopIteration` to be raised. The returned
430 value is used as an argument to construct :exc:`StopIteration` and becomes the 430 value (if any) is used as an argument to construct :exc:`StopIteration` and
431 :attr:`StopIteration.value` attribute. 431 becomes the :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_arg` | `yield_from` 447 yield_stmt: `yield_expression`
448 yield_arg: "yield" [`expression_list`] 448
449 yield_from: "yield" "from" [`expression_list`] 449 The :keyword:`yield` statement is only used when defining a generator function,
450 450 and is only used in the body of the generator function. Using a :keyword:`yield`
451 The :keyword:`yield` expression is only used when defining a generator function, 451 statement in a function definition is sufficient to cause that definition to
452 and can only be used in the body of a function definition. Using a 452 create a generator function instead of a normal function.
453 :keyword:`yield` expression in a function definition is sufficient to cause that
454 definition to create a generator function instead of a normal function.
455 453
456 When a generator function is called, it returns an iterator known as a generator 454 When a generator function is called, it returns an iterator known as a generator
457 iterator, or more commonly, a generator. That generator then controls the 455 iterator, or more commonly, a generator. The body of the generator function is
eric.araujo 2011/09/21 16:25:47 I’d remove the second comma.
458 execution of the generator function. The execution starts when one of the 456 executed by calling the :func:`next` function on the generator repeatedly until
459 generator's methods is called. At that time, the execution proceeds to the first 457 it raises an exception.
460 :keyword:`yield` expression. What happens next depends on whether the simpler 458
461 :token:`yield_arg` or the more complicated :token:`yield_from` form was used. 459 When a :keyword:`yield` statement is executed, the state of the generator is
462 460 frozen and the value of :token:`expression_list` is returned to :meth:`next`'s
463 In the first case, when ``from`` is not used, the execution of the generator 461 caller. By "frozen" we mean that all local state is retained, including the
464 function is suspended again, returning the value of :token:`expression_list` to 462 current bindings of local variables, the instruction pointer, and the internal
465 generator's caller. By suspended we mean that all local state is retained, 463 evaluation stack: enough information is saved so that the next time :func:`next`
466 including the current bindings of local variables, the instruction pointer, and 464 is invoked, the function can proceed exactly as if the :keyword:`yield`
467 the internal evaluation stack. When the execution is resumed by calling one of 465 statement were just another external call.
468 the generator's methods, the function can proceed exactly as if the 466
469 :keyword:`yield` expression was just another external call. The value of the 467 The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
470 :keyword:`yield` expression after resuming depends on the method which resumed 468 :keyword:`try` ... :keyword:`finally` construct. If the generator is not
471 the execution. 469 resumed before it is finalized (by reaching a zero reference count or by being
472 470 garbage collected), the generator-iterator's :meth:`close` method will be
473 In the second case, when ``from`` is used, the :token:`expression_list` is 471 called, allowing any pending :keyword:`finally` clauses to execute.
474 expected to yield an iterator, a "sub-generator". The evaluation of the 472
eric.araujo 2011/09/21 16:25:47 I think that using “yield” here may be confusing.
475 generator is then delegated to this sub-generator. This means that the generator 473 When ``yield from expression`` is used, it treats the supplied expression as
476 function is suspended like in the first case, but calls to 474 a subiterator, producing values from it until the underlying iterator is
477 :meth:`~generator.__next__`, :meth:`~generator.send`, :meth:`~generator.throw`, 475 exhausted.
478 and :meth:`~generator.close` are propagated to the sub-generator until it is 476
479 exhausted (and raises :exc:`StopIteration`) or until it terminates through an 477 For full details of :keyword:`yield` semantics, refer to the :ref:`yieldexpr`
480 exception (which is then re-raised at the point of the original 478 section.
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()
606 479
607 .. seealso:: 480 .. seealso::
608 481
609 :pep:`0255` - Simple Generators 482 :pep:`0255` - Simple Generators
610 The proposal for adding generators and the :keyword:`yield` statement to P ython. 483 The proposal for adding generators and the :keyword:`yield` statement to P ython.
611 484
612 :pep:`0342` - Coroutines via Enhanced Generators 485 :pep:`0342` - Coroutines via Enhanced Generators
613 The proposal to enhance the API and syntax of generators, making them 486 The proposal to enhance the API and syntax of generators, making them
614 usable as simple coroutines. 487 usable as simple coroutines.
615 488
616 :pep:`0380` - Syntax for Delegating to a Subgenerator 489 :pep:`0380` - Syntax for Delegating to a Subgenerator
617 The proposal to introduce the :token:`yield_from` syntax, making delegatio n 490 The proposal to introduce the :token:`yield_from` syntax, making delegatio n
618 to sub-generators easy. 491 to sub-generators easy.
492
619 493
620 .. _raise: 494 .. _raise:
621 495
622 The :keyword:`raise` statement 496 The :keyword:`raise` statement
623 ============================== 497 ==============================
624 498
625 .. index:: 499 .. index::
626 statement: raise 500 statement: raise
627 single: exception 501 single: exception
628 pair: raising; exception 502 pair: raising; exception
629 single: __traceback__ (exception attribute) 503 single: __traceback__ (exception attribute)
630 504
631 .. productionlist:: 505 .. productionlist::
632 raise_stmt: "raise" [`expression` ["from" `expression`]] 506 raise_stmt: "raise" [`expression` ["from" `expression`]]
633 507
634 If no expressions are present, :keyword:`raise` re-raises the last exception 508 If no expressions are present, :keyword:`raise` re-raises the last exception
635 that was active in the current scope. If no exception is active in the current 509 that was active in the current scope. If no exception is active in the current
636 scope, a :exc:`TypeError` exception is raised indicating that this is an error 510 scope, a :exc:`RuntimeError` exception is raised indicating that this is an
637 (if running under IDLE, a :exc:`queue.Empty` exception is raised instead). 511 error.
638 512
639 Otherwise, :keyword:`raise` evaluates the first expression as the exception 513 Otherwise, :keyword:`raise` evaluates the first expression as the exception
640 object. It must be either a subclass or an instance of :class:`BaseException`. 514 object. It must be either a subclass or an instance of :class:`BaseException`.
641 If it is a class, the exception instance will be obtained when needed by 515 If it is a class, the exception instance will be obtained when needed by
642 instantiating the class with no arguments. 516 instantiating the class with no arguments.
643 517
644 The :dfn:`type` of the exception is the exception instance's class, the 518 The :dfn:`type` of the exception is the exception instance's class, the
645 :dfn:`value` is the instance itself. 519 :dfn:`value` is the instance itself.
646 520
647 .. index:: object: traceback 521 .. index:: object: traceback
(...skipping 471 matching lines...) Expand 10 before | Expand all | Expand 10 after
1119 enclosing scope (the scope in which a new binding should be created cannot 993 enclosing scope (the scope in which a new binding should be created cannot
1120 be determined unambiguously). 994 be determined unambiguously).
1121 995
1122 Names listed in a :keyword:`nonlocal` statement must not collide with 996 Names listed in a :keyword:`nonlocal` statement must not collide with
1123 pre-existing bindings in the local scope. 997 pre-existing bindings in the local scope.
1124 998
1125 .. seealso:: 999 .. seealso::
1126 1000
1127 :pep:`3104` - Access to Names in Outer Scopes 1001 :pep:`3104` - Access to Names in Outer Scopes
1128 The specification for the :keyword:`nonlocal` statement. 1002 The specification for the :keyword:`nonlocal` statement.
LEFTRIGHT

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