define an idiomatic way to make a generator that throws StopIteration immediately and add it to PEP8

the way to make an (aysnc)generator that immediately raises Stop(Async)Iteration immediately is to insert an unreachable `yield` statement, however there's two ways to do it:
def example(): if False: yield
or:
def example(): return yield
currently test_asyncgen.py uses both, eg:
@types.coroutine def __anext__(self): if False: yield "this is a generator-based coroutine" if self.yielded >= 2: raise StopAsyncIteration() else: self.yielded += 1 return self.yielded
or:
async def agenfn(): try: await _async_yield(1) except MyError: await _async_yield(2) return yield
the `if False: yield` version has a disadvantage in that it can be anywhere in the function, if this one is chosen then an additional caveat is that it should be the first two statements in a function if `return; yield` version has an disadvantage in that the unreachable yield could be inserted after any `return`, if this one is chosen then an additional caveat is that it should be the last two statements in a function and de-dented as much as syntactically possible.
Which alternative do you prefer? I prefer `return; yield`

One other solution is to use a `yield from` with an empty iterable, then you don't need to have an unreachable `yield`.
Le ven. 3 sept. 2021 à 09:52, Serhiy Storchaka storchaka@gmail.com a écrit :
03.09.21 10:28, Thomas Grainger пише:
the way to make an (aysnc)generator that immediately raises Stop(Async)Iteration immediately is to insert an unreachable `yield` statement, however there's two ways to do it:
I think it is too uncommon case to specify it in PEP 8.
Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/M4TIXV... Code of Conduct: http://python.org/psf/codeofconduct/

`yield from (,)` produced different byte code when I tried it, so I think it's a tad slower
Also yield from doesn't work in async generators
participants (3)
-
Antoine Rozo
-
Serhiy Storchaka
-
Thomas Grainger