Attempting to understand yield as an expression

后端 未结 5 1763
猫巷女王i
猫巷女王i 2021-01-18 14:59

I\'m playing around with generators and generator expressions and I\'m not completely sure that I understand how they work (some reference material):

>>         


        
5条回答
  •  臣服心动
    2021-01-18 15:31

    Indeed - the send method is meant to work with a generator object that is the result of a co-routine you have explicitly written. It is difficult to get some meaning to it in a generator expression - though it works.

    -- EDIT -- I had previously written this, but it is incorrecct, as yield inside generator expressions are predictable across implementations - though not mentioned in any PEP.

    generator expressions are not meant to have the yield keyword - I am not shure the behavior is even defined in this case. We could think a little and get to what is happening on your expression, to meet from where those "None"s are coming from. However, assume that as a side effect of how the yield is implemented in Python (and probably it is even implementation dependent), not as something that should be so.

    The correct form for a generator expression, in a simplified manner is:

    ( for  in  [if ])
    

    so, is evaluated for each value in the - not only is yield uneeded, as you should not use it.

    Both yield and the send methods are meant to be used in full co-routines, something like:

    def doubler():
       value = 0
       while value < 100:
           value = 2 * (yield value)
    

    And you can use it like:

    >>> a = doubler()
    >>> # Next have to be called once, so the code will run up to the first "yield"
    ... 
    >>> a.next()
    0
    >>> a.send(10)
    20
    >>> a.send(20)
    40
    >>> a.send(23)
    46
    >>> a.send(51)
    Traceback (most recent call last):
      File "", line 1, in 
    StopIteration
    >>> 
    

提交回复
热议问题