f



[Q] is 'yield from' syntax sugar for 'for'+'yield'?

--001a11c2d676870478050093a024
Content-Type: text/plain; charset=UTF-8

Question about 'yield from'.

I understand that::

    yield from xs

is syntax suger of::

    for x in xs:
      yield x

And::

    val = yield from xs

is same as::

    for x in xs:
      ret = yield x
    val = ret

Is it true? Do I understand correctly?


quote from
https://docs.python.org/3/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator
> For simple iterators, yield from iterable is essentially
> just a shortened form of for item in iterable: yield item:

--
regards,
kwatch

--001a11c2d676870478050093a024
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<div dir=3D"ltr"><div>Question about &#39;yield from&#39;.</div><div><br></=
div><div>I understand that::</div><div><br></div><div>=C2=A0 =C2=A0 yield f=
rom xs</div><div><br></div><div>is syntax suger of::</div><div><br></div><d=
iv>=C2=A0 =C2=A0 for x in xs:</div>
<div>=C2=A0 =C2=A0 =C2=A0 yield x</div><div><br></div><div>And::</div><div>=
<br></div><div>=C2=A0 =C2=A0 val =3D yield from xs</div><div><br></div><div=
>is same as::</div><div><br></div><div>=C2=A0 =C2=A0 for x in xs:</div><div=
>=C2=A0 =C2=A0 =C2=A0 ret =3D yield x</div><div>=C2=A0 =C2=A0 val =3D ret</=
div>
<div><br></div><div>Is it true? Do I understand correctly?</div><div><br></=
div><div><br></div><div>quote from <a href=3D"https://docs.python.org/3/wha=
tsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator">https://doc=
s.python.org/3/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgene=
rator</a></div>
<div>&gt; For simple iterators, yield from iterable is essentially</div><di=
v>&gt; just a shortened form of for item in iterable: yield item:</div><div=
><br></div><div>--</div><div>regards,</div><div>kwatch</div></div>

--001a11c2d676870478050093a024--
0
Makoto
8/14/2014 9:35:36 AM
comp.lang.python 77058 articles. 6 followers. Post Follow

2 Replies
659 Views

Similar Articles

[PageSpeed] 20

Makoto Kuwata <kwatch@gmail.com>:

>     val = yield from xs
>
> is same as::
>
>     for x in xs:
>       ret = yield x
>     val = ret
>
> Is it true? Do I understand correctly?

The return value is not one of the yielded values. Instead, it's the
value returned by the generator/coroutine.


Marko
0
Marko
8/14/2014 9:57:05 AM
Makoto Kuwata wrote:

> Question about 'yield from'.
> 
> I understand that::
> 
>     yield from xs
> 
> is syntax suger of::
> 
>     for x in xs:
>       yield x

Not quite syntactic sugar. For simple cases, it does exactly the same thing.
For more complicated cases, no.

Suppose you have a generator:

def spam():
    yield "Spam!"
    yield "More spam!"
    yield "Delicious spam!!!"

and you have another generator which delegates to the spam generator:

def lunch1():
    for food in spam():
        yield food
    yield "plus a fried egg"


We can now re-write the generator using "yield from":

def lunch2():
    yield from spam()
    yield "plus a fried egg"

That saves one line of code. Big deal. Here, it is pure syntactic sugar.

There are more interesting cases, where "yield from" is more powerful than
the for-loop version. Here is an example with throw:

py> it = lunch1()  # Create an iterator.
py> next(it)
'Spam!'
py> it.throw(ValueError)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in lunch1
ValueError

Notice that the ValueError is raised inside lunch1(). There is no easy way
to push the exception back inside spam(). But with "yield from", it works:

py> it = lunch2()  # New "yield from" generator.
py> next(it)
'Spam!'
py> it.throw(ValueError)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in lunch2
  File "<stdin>", line 2, in spam
ValueError


Of course, spam() is free to catch the exception and perform processing.



> And::
> 
>     val = yield from xs
> 
> is same as::
> 
>     for x in xs:
>       ret = yield x
>     val = ret

No. This is closer to what happens:


# Not exactly this.
# This is a simplified version.
try:
    for x in xs:
        yield x
except StopIteration as err:
    val = err.value


The real version is much more complicated, 39 lines of code, and deals with
generator .close() and .throw() methods, error checking, and various other
issues. That is why "yield from" was added to Python. The simple case is
too simple to care about, the complicated cases are too complicated to
expect people to write their own solutions, so it was added to the
language.



-- 
Steven

0
Steven
8/14/2014 1:43:22 PM
Reply:

Similar Artilces:

'^=' and '~='?
Hello, What is the difference between '^=' and '~='? Thanks, Duckhye ...

'is not' or '!='
A newbie question to you; what is the difference between statements like: if x is not None: and if x != None: Without any context, which one should be preferred? IMHO, the latter is more readable. On 2014-08-18 21:35, ElChino wrote: > A newbie question to you; what is the difference between statements > like: > if x is not None: > and > if x != None: > > Without any context, which one should be preferred? > IMHO, the latter is more readable. > "x == y" tells you whether x and y refer to objects that are equal. "x is y&qu...

'''''''''''''The Running Update/Append Queries Using VBA code Ordeal''''''''''''''
Hello fellow programmers, I am trying to run an append/update query from code, a command button on a form initiates the queries. the format i am using is; _____________________________________________________ SELECT "criteria" FROM "criteria" WHERE "criteria" UPDATE/APPEND "field selections" RecordSource "qryExample" = above text strings" _______________________________________________________________________ When i am running a SELECT query in this manner it works fine with no problems, and accepts the values of specified linked for...

interaction of 'with' and 'yield'
I'm wondering if a generator that is within a 'with' scope exits the 'with' when it encounters 'yield'. I would like to use a generator to implement RAII without having to syntactically enclose the code in the 'with' scope, and I am hoping that the the yield does not exit the 'with' scope and release the resource. ...

'''''''''''''The Running Update/Append Queries Using VBA code Ordeal'''''''''''''' #2
Hi, Thanks for ur help there HJ. I know how to do the tasks you specified there. I would like for the update query to use field values from some of the fields on the form (frmInvoices) such as InvoiceNumber, DateFrom, DateTo. My problem is that an append/update query can't find the values in the open Form (frmInvoices) when I specify them as; [Forms]![frmInvoices]![InvoiceNumber] a select query has no problem finding the field values on a form. please help. Aaron Hi Aaron, Could you post the entire code that you are having trouble with? Now it is not possible to see what goes wron...

if str_mo not in ('','.') and str_da not in ('','.') and str_yy not in ('','.') Any shorter ?
Hi, there. =20 I'm just curious if it ever dawned on anybody how to abbreviate this line : if str_mo not in ('','.') and str_da not in ('','.') and str_yy not in ('','.')=20 =20 Igor Kurbeko Clinical Programmer Analyst 678 336 4328 ikurbeko@atherogenics.com =20 no brain no pain =20 how about: if not (str_mo in ('','.') or str_da in ('','.') or str_yy in ('','.')) OR if not (missing(str_mo) or missing(str_da) or missing(str_yy)) Eric On 22 Oct 03 21:13:37 GMT, ikurbeko@ATHER...

A function with 'and' , 'not' , 'null' , 'car' and 'cdr'
What's this ? (defun enigma (x) (and (not (null x)) (or (null (car x)) (enigma (cdr x))))) "I suppose I should learn Lisp, but it seems so foreign." - Paul Graham, Nov 1983 On Wed, Oct 07 2015, CAI GENGYANG wrote: > What's this ? > > > (defun enigma (x) > (and (not (null x)) > (or (null (car x)) > (enigma (cdr x))))) Bad taste? It returns T if the list X contains nil as an element. It would be clearer to write (some #'null x). Helmut CAI GENGYANG ...

Re: if str_mo not in ('','.') and str_da not in ('','.') and str_yy not in ('','.') Any shorter ?
OR you could use ARRAY data new; set old; array igor $ (*) str_mo str_da str_yr; do over igor; if igor ~in (' ','.') then do; end; run; Prasad Ravi Igor Kurbeko <ikurbeko@ATHEROGENIC To: SAS-L@LISTSERV.UGA.EDU S.COM> cc: Sent by: "SAS(r) Subject: if str_mo not in ('','.') and str_da not in ('','.') and str_yy ...

error: expected '=', ',', ';', 'asm' or '__attrib
Hi I'm trying to compile an ADC Driver & come acrosss the following error. I've no experience writing drivers before, and hence have no clue how to fix it. Hope someone out there has encountered the problem & suggesst a fix for the same. The Error is I get is : qadc.c: At top level: qadc.c:97: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'qadc_read' make: *** [qadc.o] Error 1 [root@localhost qadc]# ########################################################################### ADC Driver Code ##...

error: expected '=', ',', ';', 'asm' or '__attrib
Hi I'm trying to compile an ADC Driver & come acrosss the following error. I've no experience writing drivers before, and hence have no clue how to fix it. Hope someone out there has encountered the problem & suggesst a fix for the same. The Error is I get is : qadc.c: At top level: qadc.c:97: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'qadc_read' make: *** [qadc.o] Error 1 [root@localhost qadc]# ########################################################################### ADC Driver Code ####################...

Does '!=' equivelent to 'is not'
I'm a bit confusing about whether "is not" equivelent to "!=" if a != b: ... if a is not b: ... What's the difference between "is not" and "!=" or they are the same thing? pirata wrote: > I'm a bit confusing about whether "is not" equivelent to "!=" > > if a != b: > ... > > if a is not b: > ... > > > What's the difference between "is not" and "!=" or they are the same thing? No, they are not the same thing. == and != test to see if the *value* of two ...

Override 'and' and 'or'
Is it possible to override 'and' and/or 'or'? I cannot find a special method for it... __and__ and __rand__ and __or__ and __ror__ are for binary manipulation... any proposals? Have marvelous sunday, Marco Dekker <m.aschwanden@gmail.com> wrote: > Is it possible to override 'and' and/or 'or'? I cannot find a special > method for it... __and__ and __rand__ and __or__ and __ror__ are for > binary manipulation... any proposals? If you want to customize the truth value testing you have to implement __nonzero__ " __nonzero__( self) Call...

'[OFF]' as in 'offensive'???
Hi, given that 'off-topicness' is indicated as '[OT]' and taking a look at those postings that started the threads indicated as '[OFF]' (which may both be seen as being somewhat offensive) may lead to the conclusion that '[OFF]' stands for offensiveness. I don't think that this is the intended meaning so what actually *does* '[OFF]' mean? I never came across that abbreviation before (although I have been around on the USENET for quite some time) but maybe it is worth knowing? Josef 'Jupp' Schugt NOTE: mails >100 KiB ...

difference between ',' and 'a,'
Small question. In gforth is there a difference between the words ',' and 'a,'? I'm thinking not, so perhaps another question, why have both ',' and 'a,'? Thanks Should be the same, in gforth: see , : , here cell allot ! ; ok see a, : , here cell allot ! ; ok On Friday, January 9, 2015 at 5:46:04 AM UTC-8, beeflo wrote: > Small question. In gforth is there a difference between the words ',' and 'a,'? > > I'm thinking not, so perhaps another question, why have both ',' and 'a,'...

Web resources about - [Q] is 'yield from' syntax sugar for 'for'+'yield'? - comp.lang.python

Resources last updated: 1/26/2016 3:01:24 PM