Skip to content

Commit f6cf726

Browse files
committed
Comtinue
1 parent 61bf48c commit f6cf726

1 file changed

Lines changed: 49 additions & 29 deletions

File tree

Doc/reference/expressions.rst

Lines changed: 49 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -633,18 +633,21 @@ This may be used to override a set of defaults::
633633
>>> {**defaults, **overrides}
634634
{'color': 'yellow', 'count': 8}
635635

636-
TODO:
637-
638-
.. productionlist:: python-grammar
639-
dict_display: "{" [`dict_item_list` | `dict_comprehension`] "}"
640-
dict_item_list: `dict_item` ("," `dict_item`)* [","]
641-
dict_comprehension: `dict_item` `comp_for`
642-
dict_item: `expression` ":" `expression` | "**" `or_expr`
643-
644636
.. versionadded:: 3.5
645637
Unpacking into dictionary displays, originally proposed by :pep:`448`.
646638

647639

640+
The formal grammar for dict displays is:
641+
642+
.. grammar-snippet::
643+
:group: python-grammar
644+
645+
dict: '{' [`double_starred_kvpairs`] '}'
646+
double_starred_kvpairs: ','.`double_starred_kvpair`+ [',']
647+
double_starred_kvpair: '**' `or_expr` | `kvpair`
648+
kvpair: `expression` ':' `expression`
649+
650+
648651
.. index::
649652
single: comprehensions
650653
single: for; in comprehensions
@@ -659,14 +662,23 @@ where items are computed via a set of looping and filtering instructions
659662
rather than listed explicitly.
660663

661664
In its simplest form, a comprehension consists of a single expression
662-
followed by a :keyword:`!for` clause, all enclosed in paired delimiters.
665+
followed by a :keyword:`!for` clause.
666+
The :keyword:`!for` clause has the same syntax as the header of a
667+
:ref:`for statement <for>`, without a trailing colon.
668+
663669
For example, a list of the first ten squares is::
664670

665671
>>> [x**2 for x in range(10)]
666672
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
667673

668-
The comprehension is roughly equivalent to defining and calling the following
669-
function::
674+
At run time, a list comprehension creates a new list.
675+
The expression after :keyword:`!in` must evaluate to an :term:`iterable`.
676+
For each element of this iterable, the element is bound to the :keyword:`!for`
677+
clause's target as in a :keyword:`!for` statement, then the expression
678+
before :keyword:`!for` is evaluated with the target in scope and the result
679+
is added to the new list.
680+
Thus, the example above is roughly equivalent to defining and calling
681+
the following function::
670682

671683
def make_list_of_squares(iterable):
672684
result = []
@@ -682,11 +694,11 @@ For example, here is a set of lowercase letters::
682694
>>> {x.lower() for x in ['a', 'A', 'b', 'C']}
683695
{'c', 'a', 'b'}
684696

685-
This corresponds roughly to calling this function::
697+
At run time, this corresponds roughly to calling this function::
686698

687699
def make_lowercase_set(iterable):
688700
result = set(iterable)
689-
for x in :
701+
for x in iterable:
690702
result.append(x.lower())
691703
return result
692704

@@ -695,17 +707,17 @@ This corresponds roughly to calling this function::
695707
Dictionary comprehensions start with a colon-separated key-value pair instead
696708
of an expression. For example::
697709

698-
>>> {f.__name__: f for f in [print, hex, any]}
710+
>>> {func.__name__: func for func in [print, hex, any]}
699711
{'print': <built-in function print>,
700712
'hex': <built-in function hex>,
701713
'any': <built-in function any>}
702714

703-
This corresponds roughly to::
715+
At run time, this corresponds roughly to::
704716

705717
def make_dict_mapping_names_to_functions(iterable):
706718
result = {}
707-
for f in iterable:
708-
result[f.__name__] = f
719+
for func in iterable:
720+
result[func.__name__] = func
709721
return result
710722

711723
iterable([print, hex, any])
@@ -714,9 +726,9 @@ As in other kinds of dictionary displays, the same key may be specified
714726
multiple times.
715727
Earlier values are overwritten by ones that are evaluated later.
716728

717-
There are no *tuple comprehensions*, but a similar syntax is instead used
718-
for :ref:`generator expressions <genexpr>`, from which you can construct
719-
a tuple like this::
729+
There are no *tuple comprehensions*.
730+
A similar syntax is instead used for :ref:`generator expressions <genexpr>`,
731+
from which you can construct a tuple like this::
720732

721733
>>> tuple(x**2 for x in range(10))
722734
(0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
@@ -742,7 +754,11 @@ that start with `f` is::
742754
>>> [name for name in vars(math) if name.startswith('f')]
743755
['fabs', 'factorial', 'floor', 'fma', 'fmod', 'frexp', 'fsum']
744756

745-
This roughly corresponds to defining and calling the following function::
757+
At run time, the expression after :keyword:`!if` is evaluated before
758+
each element is added to the resulting container.
759+
If the expression evaluates to false, the element is skipped.
760+
Thus, the above example roughly corresponds to defining and calling the
761+
following function::
746762

747763
def get_math_f_names(iterable):
748764
result = []
@@ -764,11 +780,11 @@ Complex comprehensions
764780

765781
Generally, a comprehension's initial :keyword:`!for` clause may be followed
766782
zero or more additional :keyword:`!for` or :keyword:`!if` clauses.
767-
For example, here is a list of names exposed by two Python modules
768-
that start with ``a``::
783+
For example, here is a list of names exposed by two Python modules,
784+
filtered to only include names that start with ``a``::
769785

770-
>>> import math
771786
>>> import array
787+
>>> import math
772788
>>> [
773789
... name
774790
... for module in [array, math]
@@ -777,7 +793,7 @@ that start with ``a``::
777793
... ]
778794
['array', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh']
779795

780-
This roughly corresponds to defining and calling::
796+
At run time, this roughly corresponds to defining and calling::
781797

782798
def get_a_names(iterable):
783799
result = []
@@ -789,8 +805,7 @@ This roughly corresponds to defining and calling::
789805

790806
get_a_names([array, math])
791807

792-
In this case, and in the simpler cases in the previous sections,
793-
the elements of the new container are those that would be produced by
808+
The elements of the new container are those that would be produced by
794809
considering each of the :keyword:`!for` or :keyword:`!if` clauses a block,
795810
nesting from left to right, and evaluating the expression to produce an
796811
element (or dictionary entry) each time the innermost block is reached.
@@ -802,7 +817,7 @@ the enclosing scope.
802817
For example::
803818

804819
>>> x = 'old value'
805-
>>> [x**2 for x in range(10)]
820+
>>> [x**2 for x in range(10)] # this `x` is local to the comprehension
806821
>>> x
807822
'old value'
808823

@@ -814,6 +829,9 @@ Subsequent :keyword:`!for` clauses and any filter condition in the
814829
leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as
815830
they may depend on the values obtained from the leftmost iterable.
816831

832+
TODO: PEP 572:
833+
..due to a limitation in CPython’s symbol table analysis process, the reference implementation raises SyntaxError for all uses of named expressions inside comprehension iterable expressions, rather than only raising them when the named expression target conflicts with one of the iteration variables in the comprehension. This could be revisited given sufficiently compelling examples, but the extra complexity needed to implement the more selective restriction doesn’t seem worthwhile for purely hypothetical use cases.
834+
817835
To ensure the comprehension always results in a container of the appropriate
818836
type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly
819837
nested scope.
@@ -837,7 +855,7 @@ This is often used for "flattening" lists, for example::
837855
>>> [*people for people in lists_of_people]
838856
['Petr', 'Blaise', 'Jarka', 'Salim', 'Bartosz']
839857

840-
This comprehension roughly corresponds to::
858+
At run time, this comprehension roughly corresponds to::
841859

842860
def flatten_names(lists_of_people):
843861
result = []
@@ -902,6 +920,8 @@ execution of the coroutine function in which it appears.
902920
Formal grammar for comprehensions
903921
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
904922

923+
The formal grammar for comprehensions is:
924+
905925
.. grammar-snippet::
906926
:group: python-grammar
907927

0 commit comments

Comments
 (0)