[Python-Dev] Tricky way of of creating a generator via a comprehension expression (original) (raw)
Nick Coghlan ncoghlan at gmail.com
Sat Nov 25 00:39:33 EST 2017
- Previous message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Next message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 25 November 2017 at 15:27, Nathaniel Smith <njs at pobox.com> wrote:
On Fri, Nov 24, 2017 at 9:04 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
def example(): comp1 = yield from [(yield x) for x in ('1st', '2nd')] comp2 = yield from [(yield x) for x in ('3rd', '4th')] return comp1, comp2 Isn't this a really confusing way of writing def example(): return [(yield '1st'), (yield '2nd')], [(yield '3rd'), (yield '4th')]
A real use case wouldn't be iterating over hardcoded tuples in the comprehensions, it would be something more like:
def example(iterable1, iterable2):
comp1 = yield from [(yield x) for x in iterable1]
comp2 = yield from [(yield x) for x in iterable2]
return comp1, comp2
Defining an interesting for loop isn't the point of the example though
- it's just to show that if you're inside a generator, you can already make a subgenerator comprehension do something sensible by sticking "yield from" in front of it (and have actually been able to do so since 3.3, when "yield from" was first introduced).
Cheers, Nick.
-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
- Previous message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Next message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]