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

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

Issue 11682: PEP 380 reference implementation for 3.3
Patch Set: Created 7 years, 8 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:
View unified diff | Download patch
OLDNEW
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_atom` 59 : | `generator_expression` | `yield_expression`
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_atom: "(" `yield_expression` ")" 320 yield_expression: "(" `yield_stmt` ")"
321 yield_expression: "yield" [`expression_list`]
322 321
323 The :keyword:`yield` expression is only used when defining a generator function, 322 The :keyword:`yield` statement appears only in generator functions and is used
324 and can only be used in the body of a function definition. Using a 323 to pause the execution of a function and pass a value to the caller. The
eric.araujo 2011/09/21 16:25:47 This file uses two spaces after dots, please do th
325 :keyword:`yield` expression in a function definition is sufficient to cause that 324 behaviour of :keyword:`yield` depends on the generator method that was called
326 definition to create a generator function instead of a normal function. 325 and is described in detail `elsewhere <yield>`_. Here, only the behaviour of
326 :keyword:`yield` as an expression is documented.
327 327
328 When a generator function is called, it returns an iterator known as a 328 When :token:`yield from <yield_from>` is used, the :attr:`~StopIteration.value`
329 generator. That generator then controls the execution of a generator function. 329 attribute of :exc:`StopIteration` used to signal the exhaustion of the
330 The execution starts when one of the generator's methods is called. At that 330 sub-generator becomes the value of the yield expression. It can be either set
331 time, the execution proceeds to the first :keyword:`yield` expression, where it 331 explicitely when raising :exc:`StopIteration`, or automatically when the
332 is suspended again, returning the value of :token:`expression_list` to 332 sub-generator is a generator, by returning a value from the sub-generator
333 generator's caller. By suspended we mean that all local state is retained, 333 function.
334 including the current bindings of local variables, the instruction pointer, and
335 the internal evaluation stack. When the execution is resumed by calling one of
336 the generator's methods, the function can proceed exactly as if the
337 :keyword:`yield` expression was just another external call. The value of the
338 :keyword:`yield` expression after resuming depends on the method which resumed
339 the execution.
340 334
341 .. index:: single: coroutine 335 When a :token:`normal yield <yield_arg>` is used, the value of the
336 :token:`yield_expression` depends on the generator method that was called. When
337 the generator's :obj:`~generator.__next__` method is used, the value of the
338 yield expression is :const:`None`, this is the most common case. When the
339 generator's :obj:`send(value) <generator.send>` method is used, the ``value``
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`.
342 341
343 All of this makes generator functions quite similar to coroutines; they yield 342 The other two generator methods cause an exception to be raised at the point of
344 multiple times, they have more than one entry point and their execution can be 343 the yield statement. :meth:`~generator.throw` takes exception details as
345 suspended. The only difference is that a generator function cannot control 344 arguments and is used to raise an arbitrary expression at the point where the
346 where should the execution continue after it yields; the control is always 345 generator function is stopped after :keyword:`yield`. :meth:`~generator.close`
347 transferred to the generator's caller. 346 is used to finalize generators and causes a :exc:`GeneratorExit` exception to be
347 raised at the point of the :keyword:`yield` statement.
348 348
349 The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a 349 The parentheses can be ommited when the :token:`yield statement <yield_stmt>`
350 :keyword:`try` ... :keyword:`finally` construct. If the generator is not 350 occurs in a top-level expression on the right-hand side of an assignment.
351 resumed before it is finalized (by reaching a zero reference count or by being
352 garbage collected), the generator-iterator's :meth:`close` method will be
353 called, allowing any pending :keyword:`finally` clauses to execute.
354
355 .. index:: object: generator
356
357 The following generator's methods can be used to control the execution of a
358 generator function:
359
360 .. index:: exception: StopIteration
361
362
363 .. method:: generator.__next__()
364
365 Starts the execution of a generator function or resumes it at the last
366 executed :keyword:`yield` expression. When a generator function is resumed
367 with a :meth:`__next__` method, the current :keyword:`yield` expression
368 always evaluates to :const:`None`. The execution then continues to the next
369 :keyword:`yield` expression, where the generator is suspended again, and the
370 value of the :token:`expression_list` is returned to :meth:`next`'s caller.
371 If the generator exits without yielding another value, a :exc:`StopIteration`
372 exception is raised.
373
374 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
375 by the built-in :func:`next` function.
376
377
378 .. method:: generator.send(value)
379
380 Resumes the execution and "sends" a value into the generator function. The
381 ``value`` argument becomes the result of the current :keyword:`yield`
382 expression. The :meth:`send` method returns the next value yielded by the
383 generator, or raises :exc:`StopIteration` if the generator exits without
384 yielding another value. When :meth:`send` is called to start the generator,
385 it must be called with :const:`None` as the argument, because there is no
386 :keyword:`yield` expression that could receive the value.
387
388
389 .. method:: generator.throw(type[, value[, traceback]])
390
391 Raises an exception of type ``type`` at the point where generator was paused,
392 and returns the next value yielded by the generator function. If the generat or
393 exits without yielding another value, a :exc:`StopIteration` exception is
394 raised. If the generator function does not catch the passed-in exception, or
395 raises a different exception, then that exception propagates to the caller.
396
397 .. index:: exception: GeneratorExit
398
399
400 .. method:: generator.close()
401
402 Raises a :exc:`GeneratorExit` at the point where the generator function was
403 paused. If the generator function then raises :exc:`StopIteration` (by
404 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
405 not catching the exception), close returns to its caller. If the generator
406 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
407 other exception, it is propagated to the caller. :meth:`close` does nothing
408 if the generator has already exited due to an exception or normal exit.
409
410 Here is a simple example that demonstrates the behavior of generators and
411 generator functions::
412
413 >>> def echo(value=None):
414 ... print("Execution starts when 'next()' is called for the first time.")
415 ... try:
416 ... while True:
417 ... try:
418 ... value = (yield value)
419 ... except Exception as e:
420 ... value = e
421 ... finally:
422 ... print("Don't forget to clean up when 'close()' is called.")
423 ...
424 >>> generator = echo(1)
425 >>> print(next(generator))
426 Execution starts when 'next()' is called for the first time.
427 1
428 >>> print(next(generator))
429 None
430 >>> print(generator.send(2))
431 2
432 >>> generator.throw(TypeError, "spam")
433 TypeError('spam',)
434 >>> generator.close()
435 Don't forget to clean up when 'close()' is called.
436
437 351
438 .. seealso:: 352 .. seealso::
439 353
440 :pep:`0255` - Simple Generators 354 The documentation for the :keyword:`yield` statement.
eric.araujo 2011/09/21 16:25:47 I’d remove the seealso section entirely; your doc
441 The proposal for adding generators and the :keyword:`yield` statement to P ython.
442
443 :pep:`0342` - Coroutines via Enhanced Generators
444 The proposal to enhance the API and syntax of generators, making them
445 usable as simple coroutines.
446
447 355
448 .. _primaries: 356 .. _primaries:
449 357
450 Primaries 358 Primaries
451 ========= 359 =========
452 360
453 .. index:: single: primary 361 .. index:: single: primary
454 362
455 Primaries represent the most tightly bound operations of the language. Their 363 Primaries represent the most tightly bound operations of the language. Their
456 syntax is: 364 syntax is:
(...skipping 891 matching lines...) Expand 10 before | Expand all | Expand 10 after
1348 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature o f 1256 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature o f
1349 descriptors, you may notice seemingly unusual behaviour in certain uses of 1257 descriptors, you may notice seemingly unusual behaviour in certain uses of
1350 the :keyword:`is` operator, like those involving comparisons between instance 1258 the :keyword:`is` operator, like those involving comparisons between instance
1351 methods, or constants. Check their documentation for more info. 1259 methods, or constants. Check their documentation for more info.
1352 1260
1353 .. [#] The ``%`` operator is also used for string formatting; the same 1261 .. [#] The ``%`` operator is also used for string formatting; the same
1354 precedence applies. 1262 precedence applies.
1355 1263
1356 .. [#] The power operator ``**`` binds less tightly than an arithmetic or 1264 .. [#] The power operator ``**`` binds less tightly than an arithmetic or
1357 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. 1265 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.
OLDNEW

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