LoLBench / cpython_16 /instruction.md
lolbench26's picture
Publish LoLBench Harbor tasks from artifact branch (part 2)
a4edccc verified
|
Raw History Blame Contribute Delete
64.7 kB

You are working in /workspace/cpython, a source tree checked out at the base commit for this task. Implement the requested behavior in the source tree, then run:

lolbench-submit

Do not stop after editing files, running tests, or describing the solution. The task is complete only when lolbench-submit has created /logs/artifacts/solution.patch. If that file does not exist, continue working and run lolbench-submit again.

That command writes your implementation diff to /logs/artifacts/solution.patch, which is the artifact the Harbor verifier will grade. Before running lolbench-submit, clean or revert any test files you created or modified; test files must not be included in the final solution.patch.

This environment has no outbound internet access — curl/wget, git fetch/clone, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources.

Now please implement the following requirements in the source tree:


PEP 798: Unpacking in Comprehensions

Abstract

This PEP proposes extending list, set, and dictionary comprehensions, as well as generator expressions, to allow unpacking notation (* and **) at the start of the expression, providing a concise way of combining an arbitrary number of iterables into one list or set or generator, or an arbitrary number of dictionaries into one dictionary, for example:

[*it for it in its]  # list with the concatenation of iterables in 'its'
{*it for it in its}  # set with the union of iterables in 'its'
{**d for d in dicts} # dict with the combination of dicts in 'dicts'
(*it for it in its)  # generator of the concatenation of iterables in 'its'

Motivation

Extended unpacking notation (* and **) from PEP 448 makes it easy to combine a few iterables or dictionaries:

[*it1, *it2, *it3]  # list with the concatenation of three iterables
{*it1, *it2, *it3}  # set with the union of three iterables
{**dict1, **dict2, **dict3}  # dict with the combination of three dicts

But if we want to similarly combine an arbitrary number of iterables, we cannot use unpacking in this same way.

That said, we do have a few options for combining multiple iterables. We could, for example, use explicit looping structures and built-in means of combination:

new_list = []
for it in its:
    new_list.extend(it)

new_set = set()
for it in its:
    new_set.update(it)

new_dict = {}
for d in dicts:
    new_dict.update(d)

def new_generator():
    for it in its:
        yield from it

Or, we could be more concise by using a comprehension with two loops:

[x for it in its for x in it]
{x for it in its for x in it}
{key: value for d in dicts for key, value in d.items()}
(x for it in its for x in it)

Or, we could use itertools.chain or itertools.chain.from_iterable:

list(itertools.chain(*its))
set(itertools.chain(*its))
dict(itertools.chain(*(d.items() for d in dicts)))
itertools.chain(*its)

list(itertools.chain.from_iterable(its))
set(itertools.chain.from_iterable(its))
dict(itertools.chain.from_iterable(d.items() for d in dicts))
itertools.chain.from_iterable(its)

Or, for all but the generator, we could use functools.reduce:

functools.reduce(operator.iconcat, its, (new_list := []))
functools.reduce(operator.ior, its, (new_set := set()))
functools.reduce(operator.ior, its, (new_dict := {}))

This PEP proposes allowing unpacking operations to be used in comprehensions as an additional alternative:

[*it for it in its]  # list with the concatenation of iterables in 'its'
{*it for it in its}  # set with the union of iterables in 'its'
{**d for d in dicts} # dict with the combination of dicts in 'dicts'
(*it for it in its)  # generator of the concatenation of iterables in 'its'

This proposal also extends to asynchronous comprehensions and generator expressions, such that, for example, (*ait async for ait in aits()) is equivalent to (x async for ait in aits() for x in ait).

Rationale

Combining multiple iterable objects together into a single object is a common task. For example, one StackOverflow post asking about flattening a list of lists has been viewed 4.6 million times, and there are several examples of code from the standard library that perform this operation (see pep798-examples). While Python provides a means of combining a small, known number of iterables using extended unpacking from PEP 448, no comparable syntax currently exists for combining an arbitrary number of iterables.

This proposal represents a natural extension of the language, paralleling existing syntactic structures: where [x, y, z] creates a list from a fixed number of values, [item for item in items] creates a list from an arbitrary number of values; this proposal extends that notion to the construction of lists that involve unpacking, making [*item for item in items] analogous to [*x, *y, *z].

We expect this syntax to be intuitive and familiar to programmers already comfortable with both comprehensions and unpacking notation. This proposal was motivated in part by a written exam in a Python programming class, where several students used the proposed notation (specifically the set version) in their solutions, assuming that it already existed in Python. This suggests that the notation represents a logical, consistent extension to Python's existing syntax. By contrast, the existing double-loop version [x for it in its for x in it] is one that students often get wrong, the natural impulse for many students being to reverse the order of the for clauses. The intuitiveness of the proposed syntax is further supported by the comment section of a Reddit post made following the initial publication of this PEP, which demonstrates support from a broader community.

Specification

Syntax

The grammar should be changed to allow the expression in list/set comprehensions and generator expressions to be preceded by a *, and allowing an alternative form of dictionary comprehension in which a double-starred expression can be used in place of a key: value pair.

This can be accomplished by updating the listcomp and setcomp rules to use star_named_expression instead of named_expression:

listcomp[expr_ty]:
    | '[' a=star_named_expression b=for_if_clauses ']'

setcomp[expr_ty]:
    | '{' a=star_named_expression b=for_if_clauses '}'

The rule for genexp would similarly need to be modified to allow a starred_expression:

genexp[expr_ty]:
    | '(' a=(assignment_expression | expression !':=' | starred_expression) b=for_if_clauses ')'

The rule for dictionary comprehensions would need to be adjusted as well, to allow for this new form:

dictcomp[expr_ty]:
    | '{' '**' a=expression b=for_if_clauses '}' { _PyAST_DictComp(a, NULL, b, EXTRA) }

In the AST, {**expr for …} is a DictComp whose key holds the unpacked expression and whose value is None; the ASDL becomes DictComp(expr key, expr? value, comprehension* generators) so value is optional.

No change should be made to the way that argument unpacking is handled in function calls, i.e., the general rule that generator expressions provided as the sole argument to functions do not require additional redundant parentheses should be retained. Note that this implies that, for example, f(*x for x in it) is equivalent to f((*x for x in it)) (see pep798-functionargs for more discussion).

* and ** should only be allowed at the top-most level of the expression in the comprehension (see pep798-moregeneral for more discussion).

Semantics: List/Set/Dict Comprehensions

The meaning of a starred expression in a list comprehension [*expr for x in it] is to treat each expression as an iterable, and concatenate them, in the same way as if they were explicitly listed via [*expr1, *expr2, ...]. Similarly, {*expr for x in it} forms a set union, as if the expressions were explicitly listed via {*expr1, *expr2, ...}; and {**expr for x in it} combines dictionaries, as if the expressions were explicitly listed via {**expr1, **expr2, ...}. These operations should retain all of the equivalent semantics for combining collections in this way (including, for example, later values replacing earlier ones in the case of a duplicated key when combining dictionaries).

Said another way, the objects created by the following comprehensions:

new_list = [*expr for x in its]
new_set = {*expr for x in its}
new_dict = {**expr for d in dicts}

should be equivalent to the objects created by the following pieces of code, respectively:

new_list = []
for x in its:
    new_list.extend(expr)

new_set = set()
for x in its:
    new_set.update(expr)

new_dict = {}
for x in dicts:
    new_dict.update(expr)

Semantics: Generator Expressions

Generator expressions using the unpacking syntax should form new generators producing values from the concatenation of the iterables given by the expressions. Specifically, the behavior is defined to be equivalent to the following (though without defining or referencing the looping variable i):

# equivalent to g = (*expr for x in it)
def generator():
    for x in it:
        for i in expr:
            yield i

g = generator()
# equivalent to g = (*expr async for x in ait())
async def generator():
    async for x in ait():
        for i in expr:
            yield i

g = generator()

See pep798-alternativegenexpsemantics for more discussion of these semantics.

Interaction with Assignment Expressions

Note that this proposal does not suggest changing the order of evaluation of the various pieces of the comprehension, nor any rules about scoping. This is particularly relevant for generator expressions that make use of the "walrus operator" := from PEP 572, which, when used in a comprehension or a generator expression, performs its variable binding in the containing scope rather than locally to the comprehension.

As an example, consider the generator that results from evaluating the expression (*(y := [i, i+1]) for i in (0, 2, 4)). This is approximately equivalent to the following generator, except that in its generator expression form, y will be bound in the containing scope instead of locally:

def generator():
    for i in (0, 2, 4):
        for j in (y := [i, i+1]):
            yield j

In this example, the subexpression (y := [i, i+1]) is evaluated exactly three times before the generator is exhausted: just after assigning i in the comprehension to 0, 2, and 4, respectively. Thus, y (in the containing scope) will be modified at those points in time:

>>> g = (*(y := [i, i+1]) for i in (0, 2, 4))
>>> y
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    y
NameError: name 'y' is not defined
>>> next(g)
0
>>> y
[0, 1]
>>> next(g)
1
>>> y
[0, 1]
>>> next(g)
2
>>> y
[2, 3]

Error Reporting

Currently, the proposed syntax generates a SyntaxError. Allowing these forms to be recognized as syntactically valid requires adjusting the grammar rules for invalid_comprehension and invalid_dict_comprehension to allow the use of * and **, respectively.

Additional specific error messages should be provided in at least the following cases:

  • Attempting to use ** in a list comprehension or generator expression should report that dictionary unpacking cannot be used in those structures, for example:

    >>> [**x for x in y]
      File "<stdin>", line 1
        [**x for x in y]
         ^^^
    SyntaxError: cannot use dict unpacking in list comprehension
    
    >>> (**x for x in y)
      File "<stdin>", line 1
        (**x for x in y)
         ^^^
    SyntaxError: cannot use dict unpacking in generator expression
    
  • The existing error message for attempting to use * in a dictionary key/value should be retained, but similar messages should be reported when attempting to use ** unpacking on a dictionary key or value, for example:

    >>> {*k: v for k,v in items}
      File "<stdin>", line 1
        {*k: v for k,v in items}
         ^^
    SyntaxError: cannot use a starred expression in a dictionary key
    
    >>> {k: *v for k,v in items}
      File "<stdin>", line 1
        {k: *v for k,v in items}
            ^^
    SyntaxError: cannot use a starred expression in a dictionary value
    
    >>> {**k: v for k,v in items}
      File "<stdin>", line 1
        {**k: v for k,v in items}
         ^^^
    SyntaxError: cannot use dict unpacking in a dictionary key
    
    >>> {k: **v for k,v in items}
      File "<stdin>", line 1
        {k: **v for k,v in items}
            ^^^
    SyntaxError: cannot use dict unpacking in a dictionary value
    
  • The phrasing of some other existing error messages should similarly be adjusted to account for the presence of the new syntax, and/or to clarify ambiguous or confusing cases relating to unpacking more generally (particularly the cases mentioned in pep798-moregeneral), for example:

    >>> [*x if x else y]
      File "<stdin>", line 1
        [*x if x else y]
         ^^^^^^^^^^^^^^
    SyntaxError: invalid starred expression. Did you forget to wrap the conditional expression in parentheses?
    
     >>> {**x if x else y}
      File "<stdin>", line 1
        {**x if x else y}
         ^^^^^^^^^^^^^^^
    SyntaxError: invalid double starred expression. Did you forget to wrap the conditional expression in parentheses?
    
    >>> [x if x else *y]
      File "<stdin>", line 1
        [x if x else *y]
                     ^
    SyntaxError: cannot unpack only part of a conditional expression
    
    >>> {x if x else **y}
      File "<stdin>", line 1
        {x if x else **y}
                     ^^
    SyntaxError: cannot use dict unpacking on only part of a conditional expression
    

Reference Implementation

The reference implementation implements this functionality, including draft documentation and additional test cases.

Backwards Compatibility

The behavior of all comprehensions that are currently syntactically valid would be unaffected by this change, so we do not anticipate much in the way of backwards-incompatibility concerns. In principle, this change would only affect code that relied on the fact that attempting to use unpacking operations in comprehensions would raise a SyntaxError, or that relied on the particular phrasing of any of the old error messages being replaced, which we expect to be rare.

One related concern is that a hypothetical future decision to change the semantics of generator expressions to make use of yield from during unpacking (delegating to generators that are being unpacked) would not be backwards-compatible because it would affect the behavior of the resulting generators when used with .send()/.asend(), .throw()/.athrow(), and .close()/.aclose(). That said, despite being backwards-incompatible, such a change would be unlikely to have a large impact because it would only affect the behavior of structures that, under this proposal, are not particularly useful. See pep798-alternativegenexpsemantics for more discussion.

Code Examples

This section shows some illustrative examples of how small pieces of code from the standard library could be rewritten to make use of this new syntax. The pep798-reference continues to pass all tests with these replacements made.

Replacing Explicit Loops

Replacing explicit loops compresses multiple lines into one, and avoids the need for defining and referencing an auxiliary variable.

  • From email/_header_value_parser.py:

    # current:
    comments = []
    for token in self:
        comments.extend(token.comments)
    return comments
    
    # proposed:
    return [*token.comments for token in self]
    
  • From shutil.py:

    # current:
    ignored_names = []
    for pattern in patterns:
        ignored_names.extend(fnmatch.filter(names, pattern))
    return set(ignored_names)
    
    # proposed:
    return {*fnmatch.filter(names, pattern) for pattern in patterns}
    
  • From http/cookiejar.py:

    # current:
    cookies = []
    for domain in self._cookies.keys():
        cookies.extend(self._cookies_for_domain(domain, request))
    return cookies
    
    # proposed:
    return [
        *self._cookies_for_domain(domain, request)
        for domain in self._cookies.keys()
    ]
    

Replacing from_iterable and Friends

While not always the right choice, replacing itertools.chain.from_iterable and map can avoid an extra level of redirection, resulting in code that follows conventional wisdom that comprehensions are generally more readable than map/filter.

  • From dataclasses.py:

    # current:
    inherited_slots = set(
        itertools.chain.from_iterable(map(_get_slots, cls.__mro__[1:-1]))
    )
    
    # proposed:
    inherited_slots = {*_get_slots(c) for c in cls.__mro__[1:-1]}
    
  • From importlib/metadata/__init__.py:

    # current:
    return itertools.chain.from_iterable(
        path.search(prepared) for path in map(FastPath, paths)
    )
    
    # proposed:
    return (*FastPath(path).search(prepared) for path in paths)
    
  • From collections/__init__.py (Counter class):

    # current:
    return _chain.from_iterable(_starmap(_repeat, self.items()))
    
    # proposed:
    return (*_repeat(elt, num) for elt, num in self.items())
    
  • From zipfile/_path/__init__.py:

    # current:
    parents = itertools.chain.from_iterable(map(_parents, names))
    
    # proposed:
    parents = (*_parents(name) for name in names)
    
  • From _pyrepl/_module_completer.py:

    # current:
    search_locations = set(chain.from_iterable(
        getattr(spec, 'submodule_search_locations', [])
        for spec in specs if spec
    ))
    
    # proposed:
    search_locations = {
        *getattr(spec, 'submodule_search_locations', [])
        for spec in specs if spec
    }
    

Replacing Double Loops in Comprehensions

Replacing double loops in comprehensions avoids the need for defining and referencing an auxiliary variable.

  • From importlib/resources/readers.py:

    # current:
    children = (child for path in self._paths for child in path.iterdir())
    
    # proposed:
    children = (*path.iterdir() for path in self._paths)
    
  • From asyncio/base_events.py:

    # current:
    exceptions = [exc for sub in exceptions for exc in sub]
    
    # proposed:
    exceptions = [*sub for sub in exceptions]
    
  • From _weakrefset.py:

    # current:
    return self.__class__(e for s in (self, other) for e in s)
    
    # proposed:
    return self.__class__(*s for s in (self, other))
    

How to Teach This

Currently, a common way to introduce the notion of comprehensions (which is employed by the Python Tutorial) is to demonstrate equivalent code. For example, this method would say that, for example, out = [expr for x in it] is equivalent to the following code:

out = []
for x in it:
    out.append(expr)

Taking this approach, we can introduce out = [*expr for x in it] as instead being equivalent to the following (which uses extend instead of append):

out = []
for x in it:
    out.extend(expr)

Set and dict comprehensions that make use of unpacking can also be introduced by a similar analogy:

# equivalent to out = {expr for x in it}
out = set()
for x in it:
    out.add(expr)

# equivalent to out = {*expr for x in it}
out = set()
for x in it:
    out.update(expr)

# equivalent to out = {k_expr: v_expr for x in it}
out = {}
for x in it:
    out[k_expr] = v_expr

# equivalent to out = {**expr for x in it}, provided that expr evaluates to
# a mapping that can be unpacked with **
out = {}
for x in it:
    out.update(expr)

And we can take a similar approach to illustrate the behavior of generator expressions that involve unpacking:

# equivalent to g = (expr for x in it)
def generator():
    for x in it:
        yield expr
g = generator()

# equivalent to g = (*expr for x in it)
def generator():
    for x in it:
        yield from expr
g = generator()

We can then generalize from these specific examples to the idea that, wherever a non-starred comprehension/genexp would use an operator that adds a single element to a collection, the starred would instead use an operator that adds multiple elements to that collection.

Alternatively, we don't need to think of the two ideas as separate; instead, with the new syntax, we can think of out = [...x... for x in it] as equivalent to the following [1] (where ...x... is a stand-in for arbitrary code), regardless of whether or not ...x... uses *:

out = []
for x in it:
    out.extend([...x...])

Similarly, we can think of out = {...x... for x in it} as equivalent to the following code, regardless of whether or not ...x... uses * or ** or ::

out = set()  # or out = {}
for x in it:
    out.update({...x...})

These examples are equivalent in the sense that the output they produce would be the same in both the version with the comprehension and the version without it, but note that the non-comprehension version is slightly less efficient due to making new lists/sets/dictionaries before each extend or update, which is unnecessary in the version that uses comprehensions.

Rejected Alternative Proposals

The primary goal when thinking through the specification above was consistency with existing norms around unpacking and comprehensions / generator expressions. One way to interpret this is that the goal was to write the specification so as to require the smallest possible change(s) to the existing grammar and code generation, letting the existing code inform the surrounding semantics.

Below we discuss some of the common concerns/alternative proposals that came up in discussions but that are not included in this proposal.

Starred Generators as Function Arguments

One common concern that has arisen multiple times (not only in the discussion threads linked above but also in previous discussions around this same idea) is a possible syntactical ambiguity when passing a starred generator as the sole argument to f(*x for x in y). In the original PEP 448, this ambiguity was cited as a reason for not including a similar generalization as part of the proposal.

This proposal suggests that f(*x for x in y) should be interpreted as f((*x for x in y)) and should not attempt further unpacking of the resulting generator, but several alternatives were suggested in our discussion (and/or have been suggested in the past), including:

  • interpreting f(x for x in y) as f((x for x in y),
  • interpreting f(x for x in y) as f((*x for x in y)), or
  • continuing to raise a SyntaxError for f(*x for x in y) even if the other aspects of this proposal are accepted.

The reason to prefer this proposal over these alternatives is the preservation of existing conventions for punctuation around generator expressions. Currently, the general rule is that generator expressions must be wrapped in parentheses except when provided as the sole argument to a function, and this proposal suggests maintaining that rule even as we allow more kinds of generator expressions. This option maintains a full symmetry between comprehensions and generator expressions that use unpacking and those that don't.

Currently, we have the following conventions:

f([x for x in y])  # pass in a single list
f({x for x in y})  # pass in a single set
f(x for x in y)  # pass in a single generator (no additional parentheses required around genexp)

f(*[x for x in y])  # pass in elements from the list separately
f(*{x for x in y})  # pass in elements from the set separately
f(*(x for x in y))  # pass in elements from the generator separately (parentheses required)

This proposal opts to maintain those conventions even when the comprehensions make use of unpacking:

f([*x for x in y])  # pass in a single list
f({*x for x in y})  # pass in a single set
f(*x for x in y)  # pass in a single generator (no additional parentheses required around genexp)

f(*[*x for x in y])  # pass in elements from the list separately
f(*{*x for x in y})  # pass in elements from the set separately
f(*(*x for x in y))  # pass in elements from the generator separately (parentheses required)

Further Generalizing Unpacking Operators

Another suggestion that came out of the discussion involved further generalizing the * beyond simply allowing it to be used to unpack the expression in a comprehension. Two main flavors of this extension were considered:

  • making * and ** true unary operators that create a new kind of Unpackable object (or similar), which comprehensions could treat by unpacking it but which could also be used in other contexts; or

  • continuing to allow * and ** only in the places they are allowed elsewhere in this proposal (expression lists, comprehensions, generator expressions, and argument lists), but also allow them to be used in subexpressions within a comprehension, allowing, for example, the following as a way to flatten a list that contains some iterables but some non-iterable objects:

    [*x if isinstance(x, Iterable) else x for x in [[1,2,3], 4]]
    

These variants were considered substantially more complex (both to understand and to implement) and of only marginal utility, so neither is included in this PEP. As such, these forms should continue to raise a SyntaxError, but with a new error message as described above, though it should not be ruled out as a consideration for future proposals.

Alternative Generator Expression Semantics

Another point of discussion centered around the semantics of unpacking in generator expressions, particularly the relationship between the semantics of synchronous and asynchronous generator expressions given that async generators do not support yield from (see the section of PEP 525 on Asynchronous yield from).

The core question centered around whether sync and async generator expressions should use yield from (or an equivalent) when unpacking, as opposed to an explicit loop. The main difference between these options is whether the resulting generator delegates to the objects being unpacked, which would affect the behavior of these generator expressions when used with .send()/.asend(), .throw()/.athrow(), and .close()/.aclose() in the case where the objects being unpacked are themselves generators. The differences between these options are summarized in pep798-appendix-yieldfrom.

Several reasonable options were considered, none of which was a clear winner in a poll in the Discourse thread. Beyond the proposal outlined above, the following were also considered:

  1. Using yield from for unpacking in synchronous generator expressions but using an explicit loop in asynchronous generator expressions (as proposed in the original draft of this PEP).

    This strategy would have allowed unpacking in generator expressions to closely mimic a popular way of writing generators that perform this operation (using yield from), but it would also have created an asymmetry between synchronous and asynchronous versions, and also between this new syntax and itertools.chain and the double-loop version.

  2. Using yield from for unpacking in synchronous generator expressions and mimicking the behavior of yield from for unpacking in async generator expressions.

    This strategy would also make unpacking in synchronous and asynchronous generators behave symmetrically, but it would also be more complex, enough so that the cost may not be worth the benefit, particularly in the absence of a compelling use case for delegation.

  3. Using yield from for unpacking in synchronous generator expressions, and disallowing unpacking in asynchronous generator expressions until they support yield from.

    This strategy could possibly reduce friction if asynchronous generator expressions do gain support for yield from in the future by making sure that any decision made at that point would be fully backwards-compatible, but in the meantime, it would result in an even bigger discrepancy between synchronous and asynchronous generator expressions than option 1.

  4. Disallowing unpacking in all generator expressions.

    This would retain symmetry between the two cases, but with the downside of losing an expressive form and reducing symmetry between list/set comprehensions and generator expressions.

Each of these options (including the one presented in this PEP) has its benefits and drawbacks, with no option being clearly superior on all fronts. The semantics proposed in pep798-genexpsemantics above represent a reasonable compromise by allowing exactly the same kind of unpacking in synchronous and asynchronous generator expressions and retaining an existing property of generator expressions (that they do not delegate to subgenerators).

This decision should be revisited in the event that asynchronous generators receive support for yield from in the future, in which case adjusting the semantics of unpacking in generator expressions to use yield from should be considered.

Concerns and Disadvantages

Although the general consensus from the discussion thread seemed to be that this syntax was clear and intuitive, several concerns and potential downsides were raised as well. This section aims to summarize those concerns.

  • Overlap with existing alternatives: While the proposed syntax represents a consistent extension to the language and is likely to result in more-concise code, there are already several ways to accomplish this same thing in Python.
  • Function call ambiguity: Expressions like f(*x for x in y) may initially appear ambiguous, as it's not obvious whether the intent is to unpack the generator or to pass it as a single argument. Although this proposal retains existing conventions by treating that form as equivalent to f((*x for x in y)), that equivalence may not be immediately obvious.
  • Potential for overuse or abuse: Complex uses of unpacking in comprehensions could obscure logic that may be clearer in an explicit loop. While this is already a concern with comprehensions more generally, the addition of * and ** may make particularly complex uses even more difficult to read and understand at a glance. For example, while these situations are likely rare, comprehensions that use unpacking in multiple ways can make it difficult to know what's being unpacked and when, e.g., f(*(*x for *x, _ in list_of_lists)).
  • Unclear limitation of scope: This proposal restricts unpacking to the top level of the comprehension expression, but some users may expect that the unpacking operator is being further generalized as discussed in pep798-moregeneral.
  • Effect on External Tools: As with any change to Python's syntax, making this change would create work for maintainers of code formatters, linters, type checkers, etc., to make sure that the new syntax is supported.

Appendix: Other Languages

Quite a few other languages support this kind of flattening with syntax similar to what is already available in Python, but support for using unpacking syntax within comprehensions is rare. This section provides a brief summary of support for similar syntax in a few other languages.

Many languages that support comprehensions support double loops:

# python
[x for xs in [[1,2,3], [], [4,5]] for x in xs * 2]
-- haskell
[x | xs <- [[1,2,3], [], [4,5]], x <- xs ++ xs]
# julia
[x for xs in [[1,2,3], [], [4,5]] for x in [xs; xs]]
; clojure
(for [xs [[1 2 3] [] [4 5]] x (concat xs xs)] x)

Several other languages (even those without comprehensions) support these operations via a built-in function or method to support flattening of nested structures:

# python
list(itertools.chain(*(xs*2 for xs in [[1,2,3], [], [4,5]])))
// javascript
[[1,2,3], [], [4,5]].flatMap(xs => [...xs, ...xs])
-- haskell
concat (map (\x -> x ++ x) [[1,2,3], [], [4,5]])
# ruby
[[1, 2, 3], [], [4, 5]].flat_map {|e| e * 2}

However, languages that support both comprehension and unpacking do not tend to allow unpacking within a comprehension. For example, the following expression in Julia currently leads to a syntax error:

[xs... for xs in [[1,2,3], [], [4,5]]]

As one counterexample, support for a similar syntax was recently added to Civet. For example, the following is a valid comprehension in Civet, making use of JavaScript's ... syntax for unpacking:

for xs of [[1,2,3], [], [4,5]] then ...(xs++xs)

Appendix: Semantics of Generator Delegation

One of the common questions about the semantics outlined above had to do with the difference between using yield from when unpacking inside of a generator expression, versus using an explicit loop. Because this is a fairly-advanced feature of generators, this appendix attempts to summarize some of the key differences between generators that use yield from and those that use explicit loops.

Basic Behavior

For simple iteration over values, which we expect to be by far the most-common use of unpacking in generator expressions, both approaches produce identical results:

def yield_from(iterables):
    for iterable in iterables:
        yield from iterable

def explicit_loop(iterables):
    for iterable in iterables:
        for item in iterable:
            yield item

# Both produce the same sequence of values
x = list(yield_from([[1, 2], [3, 4]]))
y = list(explicit_loop([[1, 2], [3, 4]]))
print(x == y)  # prints True

Advanced Generator Protocol Differences

The differences become apparent when using the advanced generator protocol methods .send(), .throw(), and .close(), and when the sub-iterables are themselves generators rather than simple sequences. In these cases, the yield from version results in the associated signal reaching the subgenerator, but the version with the explicit loop does not.

Delegation with .send()

def sub_generator():
    x = yield "first"
    yield f"received: {x}"
    yield "last"

def yield_from():
    yield from sub_generator()

def explicit_loop():
    for item in sub_generator():
        yield item

# With yield from, values are passed through to sub-generator
gen1 = yield_from()
print(next(gen1))  # prints "first"
print(gen1.send("hello"))  # prints "received: hello"
print(next(gen1))  # prints "last"

# With explicit loop, .send() affects the outer generator; values don't reach the sub-generator
gen2 = explicit_loop()
print(next(gen2))  # prints "first"
print(gen2.send("hello"))  # prints "received: None" (sub-generator receives None instead of "hello")
print(next(gen2))  # prints "last"

Exception Handling with .throw()

def sub_generator_with_exception_handling():
    try:
        yield "first"
        yield "second"
    except ValueError as e:
        yield f"caught: {e}"

def yield_from():
    yield from sub_generator_with_exception_handling()

def explicit_loop():
    for item in sub_generator_with_exception_handling():
        yield item

# With yield from, exceptions are passed to sub-generator
gen1 = yield_from()
print(next(gen1))  # prints "first"
print(gen1.throw(ValueError("test")))  # prints "caught: test"

# With explicit loop, exceptions affect the outer generator only
gen2 = explicit_loop()
print(next(gen2))  # prints "first"
print(gen2.throw(ValueError("test")))  # ValueError is raised; sub-generator doesn't see it

Generator Cleanup with .close()

# With yield from, GeneratorExit is passed through to sub-generator
gen1 = yield_from()
print(next(gen1))  # prints "first"
gen1.close()  # closes sub-generator and then outer generator

# With explicit loop, GeneratorExit goes to outer generator only
gen2 = explicit_loop()
print(next(gen2))  # prints "first"
gen2.close()  # only closes outer generator

print('program finished; GC will close the explicit loop subgenerator')
# second inner generator closes when GC closes it at the end

References

[1]

Message from Guido van Rossum

Linked PEP 448 — Additional Unpacking Generalizations

Abstract

This PEP proposes extended usages of the * iterable unpacking operator and ** dictionary unpacking operators to allow unpacking in more positions, an arbitrary number of times, and in function calls and displays.

Function calls are proposed to support an arbitrary number of unpackings rather than just one:

>>> print(*[1], *[2], 3)
1 2 3
>>> dict(**{'x': 1}, y=2, **{'z': 3})
{'x': 1, 'y': 2, 'z': 3}

Unpacking is proposed to be allowed inside tuple, list, set, and dictionary displays:

>>> *range(4), 4
(0, 1, 2, 3, 4)
>>> [*range(4), 4]
[0, 1, 2, 3, 4]
>>> {*range(4), 4}
{0, 1, 2, 3, 4}
>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}

In dictionaries, later values will always override earlier ones:

>>> {'x': 1, **{'x': 2}}
{'x': 2}

>>> {**{'x': 2}, 'x': 1}
{'x': 1}

This PEP does not include unpacking operators inside list, set and dictionary comprehensions although this has not been ruled out for future proposals.

Rationale

Current usage of the * iterable unpacking operator features unnecessary restrictions that can harm readability.

Unpacking multiple times has an obvious rationale. When you want to unpack several iterables into a function definition or follow an unpack with more positional arguments, the most natural way would be to write:

function(**kw_arguments, **more_arguments)

function(*arguments, argument)

Simple examples where this is useful are print and str.format. Instead, you could be forced to write:

kwargs = dict(kw_arguments)
kwargs.update(more_arguments)
function(**kwargs)

args = list(arguments)
args.append(arg)
function(*args)

or, if you know to do so:

from collections import ChainMap
function(**ChainMap(more_arguments, arguments))

from itertools import chain
function(*chain(args, [arg]))

which add unnecessary line-noise and, with the first methods, causes duplication of work.

There are two primary rationales for unpacking inside of containers. Firstly there is a symmetry of assignment, where fst, *other, lst = elems and elems = fst, *other, lst are approximate inverses, ignoring the specifics of types. This, in effect, simplifies the language by removing special cases.

Secondly, it vastly simplifies types of "addition" such as combining dictionaries, and does so in an unambiguous and well-defined way:

combination = {**first_dictionary, "x": 1, "y": 2}

instead of:

combination = first_dictionary.copy()
combination.update({"x": 1, "y": 2})

which is especially important in contexts where expressions are preferred. This is also useful as a more readable way of summing iterables into a list, such as my_list + list(my_tuple) + list(my_range) which is now equivalent to just [*my_list, *my_tuple, *my_range].

Specification

Function calls may accept an unbounded number of * and ** unpackings. There will be no restriction of the order of positional arguments with relation to * unpackings nor any restriction of the order of keyword arguments with relation to ** unpackings.

Function calls continue to have the restriction that keyword arguments must follow positional arguments and ** unpackings must additionally follow * unpackings.

Currently, if an argument is given multiple times — such as a positional argument given both positionally and by keyword — a TypeError is raised. This remains true for duplicate arguments provided through multiple ** unpackings, e.g. f(**{'x': 2}, **{'x': 3}), except that the error will be detected at runtime.

A function looks like this:

function(
    argument or *args, argument or *args, ...,
    kwargument or *args, kwargument or *args, ...,
    kwargument or **kwargs, kwargument or **kwargs, ...
)

Tuples, lists, sets and dictionaries will allow unpacking. This will act as if the elements from unpacked items were inserted in order at the site of unpacking, much as happens in unpacking in a function-call. Dictionaries require ** unpacking; all the others require * unpacking.

The keys in a dictionary remain in a right-to-left priority order, so {**{'a': 1}, 'a': 2, **{'a': 3}} evaluates to {'a': 3}. There is no restriction on the number or position of unpackings.

Disadvantages

The allowable orders for arguments in a function call are more complicated than before. The simplest explanation for the rules may be "positional arguments precede keyword arguments and ** unpacking; * unpacking precedes ** unpacking".

Whilst *elements, = iterable causes elements to be a list, elements = *iterable, causes elements to be a tuple. The reason for this may confuse people unfamiliar with the construct.

Concerns have been raised about the unexpected difference between duplicate keys in dictionaries being allowed but duplicate keys in function call syntax raising an error. Although this is already the case with current syntax, this proposal might exacerbate the issue. It remains to be seen how much of an issue this is in practice.

Variations

The PEP originally considered whether the ordering of argument types in a function call (positional, keyword, * or **) could become less strict. This met little support so the idea was shelved.

Earlier iterations of this PEP allowed unpacking operators inside list, set, and dictionary comprehensions as a flattening operator over iterables of containers:

>>> ranges = [range(i) for i in range(5)]
>>> [*item for item in ranges]
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]

>>> {*item for item in ranges}
{0, 1, 2, 3}

This was met with a mix of strong concerns about readability and mild support. In order not to disadvantage the less controversial aspects of the PEP, this was not accepted with the rest of the proposal.

Unbracketed comprehensions in function calls, such as f(x for x in it), are already valid. These could be extended to:

f(*x for x in it) == f((*x for x in it))
f(**x for x in it) == f({**x for x in it})

However, it wasn't clear if this was the best behaviour or if it should unpack into the arguments of the call to f. Since this is likely to be confusing and is of only very marginal utility, it is not included in this PEP. Instead, these will throw a SyntaxError and comprehensions with explicit brackets should be used instead.

Source: https://peps.python.org/pep-0448/

Linked PEP 572 — Assignment Expressions

Abstract

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr.

As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value).

During discussion of this PEP, the operator became informally known as "the walrus operator". The construct's formal name is "Assignment Expressions" (as per the PEP title), but they may also be referred to as "Named Expressions" (e.g. the CPython reference implementation uses that name internally).

Rationale

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.

Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few name := markers. Removing the need to refactor reduces the likelihood that the code be inadvertently changed as part of debugging (a common cause of Heisenbugs), and is easier to dictate to another programmer.

Syntax and semantics

In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier.

The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:

# Handle a matched regex
if (match := pattern.search(data)) is not None:
    # Do something with match

# A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
   process(chunk)

# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]

# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]

Exceptional cases

There are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:

  • Unparenthesized assignment expressions are prohibited at the top level of an expression statement. Example:

    y := f(x)  # INVALID
    (y := f(x))  # Valid, though not recommended
    

    This rule is included to simplify the choice for the user between an assignment statement and an assignment expression -- there is no syntactic position where both are valid.

  • Unparenthesized assignment expressions are prohibited at the top level of the right hand side of an assignment statement. Example:

    y0 = y1 := f(x)  # INVALID
    y0 = (y1 := f(x))  # Valid, though discouraged
    

    Again, this rule is included to avoid two visually similar ways of saying the same thing.

  • Unparenthesized assignment expressions are prohibited for the value of a keyword argument in a call. Example:

    foo(x = y := f(x))  # INVALID
    foo(x=(y := f(x)))  # Valid, though probably confusing
    

    This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

  • Unparenthesized assignment expressions are prohibited at the top level of a function default value. Example:

    def foo(answer = p := 42):  # INVALID
        ...
    def foo(answer=(p := 42)):  # Valid, though not great style
        ...
    

    This rule is included to discourage side effects in a position whose exact semantics are already confusing to many users (cf. the common style recommendation against mutable default values), and also to echo the similar prohibition in calls (the previous bullet).

  • Unparenthesized assignment expressions are prohibited as annotations for arguments, return values and assignments. Example:

    def foo(answer: p := 42 = 5):  # INVALID
        ...
    def foo(answer: (p := 42) = 5):  # Valid, but probably never useful
        ...
    

    The reasoning here is similar to the two previous cases; this ungrouped assortment of symbols and operators composed of : and = is hard to read correctly.

  • Unparenthesized assignment expressions are prohibited in lambda functions. Example:

    (lambda: x := 1) # INVALID
    lambda: (x := 1) # Valid, but unlikely to be useful
    (x := lambda: 1) # Valid
    lambda line: (m := re.match(pattern, line)) and m.group(1) # Valid
    

    This allows lambda to always bind less tightly than :=; having a name binding at the top level inside a lambda function is unlikely to be of value, as there is no way to make use of it. In cases where the name will be used more than once, the expression is likely to need parenthesizing anyway, so this prohibition will rarely affect code.

  • Assignment expressions inside of f-strings require parentheses. Example:

    >>> f'{(x:=10)}'  # Valid, uses assignment expression
    '10'
    >>> x = 10
    >>> f'{x:=10}'    # Valid, passes '=10' to formatter
    '        10'
    

    This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : to indicate formatting options. To preserve backwards compatibility, assignment operator usage inside of f-strings must be parenthesized. As noted above, this usage of the assignment operator is not recommended.

Scope of the target

An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as a scope for this purpose.

There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as "comprehensions") binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the containing scope of a nested comprehension is the scope that contains the outermost comprehension. A lambda counts as a containing scope.

The motivation for this special case is twofold. First, it allows us to conveniently capture a "witness" for an any() expression, or a counterexample for all(), for example:

if any((comment := line).startswith('#') for line in lines):
    print("First comment:", comment)
else:
    print("There are no comments")

if all((nonblank := line).strip() == '' for line in lines):
    print("All lines are blank")
else:
    print("First non-blank line:", nonblank)

Second, it allows a compact way of updating mutable state from a comprehension, for example:

# Compute partial sums in a list comprehension
total = 0
partial_sums = [total := total + v for v in values]
print("Total:", total)

However, an assignment expression target name cannot be the same as a for-target name appearing in any comprehension containing the assignment expression. The latter names are local to the comprehension in which they appear, so it would be contradictory for a contained use of the same name to refer to the scope containing the outermost comprehension instead.

For example, [i := i+1 for i in range(5)] is invalid: the for i part establishes that i is local to the comprehension, but the i := part insists that i is not local to the comprehension. The same reason makes these examples invalid too:

[[(j := j) for i in range(5)] for j in range(5)] # INVALID
[i := 0 for i, j in stuff]                       # INVALID
[i+1 for i in (i := stuff)]                      # INVALID

While it's technically possible to assign consistent semantics to these cases, it's difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation will ensure that such cases raise SyntaxError, rather than executing with implementation defined behaviour.

This restriction applies even if the assignment expression is never executed:

[False and (i := 0) for i, j in stuff]     # INVALID
[i for i, j in stuff if True or (j := 1)]  # INVALID

For the comprehension body (the part before the first "for" keyword) and the filter expression (the part after "if" and before any nested "for"), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions.

Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each "in", and before any subsequent "if" or "for" keyword):

[i+1 for i in (j := stuff)]                    # INVALID
[i+1 for i in range(2) for j in (k := stuff)]  # INVALID
[i+1 for i in [j for j in (k := stuff)]]       # INVALID
[i+1 for i in (lambda: (j := stuff))()]        # INVALID

A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class's scope, the assignment expression is expressly invalid. This case also raises SyntaxError:

class Example:
    [(j := i) for i in range(5)]  # INVALID

(The reason for the latter exception is the implicit function scope created for comprehensions -- there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.)

Relative precedence of :=

The := operator groups more tightly than a comma in all syntactic positions where it is legal, but less tightly than all other operators, including or, and, not, and conditional expressions (A if C else B). As follows from section "Exceptional cases" above, it is never allowed at the same level as =. In case a different grouping is desired, parentheses should be used.

The := operator may be used directly in a positional function call argument; however it is invalid directly in a keyword argument.

Some examples to clarify what's technically valid or invalid:

# INVALID
x := 0

# Valid alternative
(x := 0)

# INVALID
x = y := 0

# Valid alternative
x = (y := 0)

# Valid
len(lines := f.readlines())

# Valid
foo(x := 3, cat='vector')

# INVALID
foo(cat=category := 'vector')

# Valid alternative
foo(cat=(category := 'vector'))

Most of the "valid" examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable.

This PEP recommends always putting spaces around :=, similar to PEP 8's recommendation for = when used for assignment, whereas the latter actually discourages spaces around = used for keyword arguments.

Source: https://peps.python.org/pep-0572/

Linked PEP 525 — Asynchronous Generators

Abstract

PEP 492 introduced support for native coroutines and async/await syntax to Python 3.5. It is proposed here to extend Python's asynchronous capabilities by adding support for asynchronous generators.

Rationale and Goals

Regular generators (introduced in PEP 255) enabled an elegant way of writing complex data producers and have them behave like an iterator.

However, currently there is no equivalent concept for the asynchronous iteration protocol (async for). This makes writing asynchronous data producers unnecessarily complex, as one must define a class that implements __aiter__ and __anext__ to be able to use it in an async for statement.

Essentially, the goals and rationale for PEP 255, applied to the asynchronous execution case, hold true for this proposal as well.

Performance is an additional point for this proposal: in our testing of the reference implementation, asynchronous generators are 2x faster than an equivalent implemented as an asynchronous iterator.

As an illustration of the code quality improvement, consider the following class that prints numbers with a given delay once iterated:

class Ticker:
    """Yield numbers from 0 to `to` every `delay` seconds."""

    def __init__(self, delay, to):
        self.delay = delay
        self.i = 0
        self.to = to

    def __aiter__(self):
        return self

    async def __anext__(self):
        i = self.i
        if i >= self.to:
            raise StopAsyncIteration
        self.i += 1
        if i:
            await asyncio.sleep(self.delay)
        return i

The same can be implemented as a much simpler asynchronous generator:

async def ticker(delay, to):
    """Yield numbers from 0 to `to` every `delay` seconds."""
    for i in range(to):
        yield i
        await asyncio.sleep(delay)

Specification

This proposal introduces the concept of asynchronous generators to Python.

This specification presumes knowledge of the implementation of generators and coroutines in Python (PEP 342, PEP 380 and PEP 492).

Asynchronous Generators

A Python generator is any function containing one or more yield expressions:

def func():            # a function
    return

def genfunc():         # a generator function
    yield

We propose to use the same approach to define asynchronous generators:

async def coro():      # a coroutine function
    await smth()

async def asyncgen():  # an asynchronous generator function
    await smth()
    yield 42

The result of calling an asynchronous generator function is an asynchronous generator object, which implements the asynchronous iteration protocol defined in PEP 492.

It is a SyntaxError to have a non-empty return statement in an asynchronous generator.

Support for Asynchronous Iteration Protocol

The protocol requires two special methods to be implemented:

  1. An __aiter__ method returning an asynchronous iterator.
  2. An __anext__ method returning an awaitable object, which uses StopIteration exception to "yield" values, and StopAsyncIteration exception to signal the end of the iteration.

Asynchronous generators define both of these methods. Let's manually iterate over a simple asynchronous generator:

async def genfunc():
    yield 1
    yield 2

gen = genfunc()

assert gen.__aiter__() is gen

assert await gen.__anext__() == 1
assert await gen.__anext__() == 2

await gen.__anext__()  # This line will raise StopAsyncIteration.

Finalization

PEP 492 requires an event loop or a scheduler to run coroutines. Because asynchronous generators are meant to be used from coroutines, they also require an event loop to run and finalize them.

Asynchronous generators can have try..finally blocks, as well as async with. It is important to provide a guarantee that, even when partially iterated, and then garbage collected, generators can be safely finalized.

To solve this problem we propose to do the following:

  1. Implement an aclose method on asynchronous generators returning a special awaitable. When awaited it throws a GeneratorExit into the suspended generator and iterates over it until either a GeneratorExit or a StopAsyncIteration occur.

    This is very similar to what the close() method does to regular Python generators, except that an event loop is required to execute aclose().

  2. Raise a RuntimeError, when an asynchronous generator executes a yield expression in its finally block (using await is fine, though):

    async def gen():
        try:
            yield
        finally:
            await asyncio.sleep(1)   # Can use 'await'.
    
            yield                    # Cannot use 'yield',
                                     # this line will trigger a
                                     # RuntimeError.
    
  3. Add two new methods to the sys module: set_asyncgen_hooks() and get_asyncgen_hooks().

The idea behind sys.set_asyncgen_hooks() is to allow event loops to intercept asynchronous generators iteration and finalization, so that the end user does not need to care about the finalization problem, and everything just works.

sys.set_asyncgen_hooks() accepts two arguments:

  • firstiter: a callable which will be called when an asynchronous generator is iterated for the first time.

  • finalizer: a callable which will be called when an asynchronous generator is about to be GCed.

When an asynchronous generator is iterated for the first time, it stores a reference to the current finalizer.

When an asynchronous generator is about to be garbage collected, it calls its cached finalizer. The assumption is that the finalizer will schedule an aclose() call with the loop that was active when the iteration started.

Asynchronous Generator Object

The object is modeled after the standard Python generator object. Essentially, the behaviour of asynchronous generators is designed to replicate the behaviour of synchronous generators, with the only difference in that the API is asynchronous.

The following methods and properties are defined:

  1. agen.__aiter__(): Returns agen.

  2. agen.__anext__(): Returns an awaitable, that performs one asynchronous generator iteration when awaited.

  3. agen.asend(val): Returns an awaitable, that pushes the val object in the agen generator. When the agen has not yet been iterated, val must be None.

  4. agen.athrow(typ, [val, [tb]]): Returns an awaitable, that throws an exception into the agen generator.

  5. agen.aclose(): Returns an awaitable, that throws a GeneratorExit exception into the generator. The awaitable can either return a yielded value, if agen handled the exception, or agen will be closed and the exception will propagate back to the caller.

  6. agen.__name__ and agen.__qualname__: readable and writable name and qualified name attributes.

  7. agen.ag_await: The object that agen is currently awaiting on, or None. This is similar to the currently available gi_yieldfrom for generators and cr_await for coroutines.

  8. agen.ag_frame, agen.ag_running, and agen.ag_code: defined in the same way as similar attributes of standard generators.

StopIteration and StopAsyncIteration are not propagated out of asynchronous generators, and are replaced with a RuntimeError.

Backwards Compatibility

The proposal is fully backwards compatible.

In Python 3.5 it is a SyntaxError to define an async def function with a yield expression inside, therefore it's safe to introduce asynchronous generators in 3.6.

Design Considerations

Asynchronous list/dict/set comprehensions

Syntax for asynchronous comprehensions is unrelated to the asynchronous generators machinery, and should be considered in a separate PEP.

Asynchronous yield from

While it is theoretically possible to implement yield from support for asynchronous generators, it would require a serious redesign of the generators implementation.

yield from is also less critical for asynchronous generators, since there is no need provide a mechanism of implementing another coroutines protocol on top of coroutines. And to compose asynchronous generators a simple async for loop can be used:

async def g1():
    yield 1
    yield 2

async def g2():
    async for v in g1():
        yield v

Why the asend() and athrow() methods are necessary

They make it possible to implement concepts similar to contextlib.contextmanager using asynchronous generators. For instance, with the proposed design, it is possible to implement the following pattern:

@async_context_manager
async def ctx():
    await open()
    try:
        yield
    finally:
        await close()

async with ctx():
    await ...

Another reason is that it is possible to push data and throw exceptions into asynchronous generators using the object returned from __anext__ object, but it is hard to do that correctly. Adding explicit asend() and athrow() will pave a safe way to accomplish that.

In terms of implementation, asend() is a slightly more generic version of __anext__, and athrow() is very similar to aclose(). Therefore, having these methods defined for asynchronous generators does not add any extra complexity.

Source: https://peps.python.org/pep-0525/