4

There are some examples of python functions that contains a yield - but without any parameter.

Examples: here and here and here.

So what does that yield yield then? How does it work?

Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

4

So what does that yield yield then?

As commented by Paul Becotte yield without a value yields None.

How does it work?

From the Python Generators wiki, the yield syntax is the syntactic sugar that you need to tell Python to generate an iterable object from your function. It converts:

# a generator that yields items instead of returning a list
def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

into:

# Using the generator pattern (an iterable)
class firstn(object):
    def __init__(self, n):
        self.n = n
        self.num, self.nums = 0, []

    def __iter__(self):
        return self

    # Python 3 compatibility
    def __next__(self):
        return self.next()

    def next(self):
        if self.num < self.n:
            cur, self.num = self.num, self.num+1
            return cur
        else:
            raise StopIteration()

So I could just remove it? — comment

Without the yield keyword it's just a function that returns None.

Carrying on further down in the wiki, there is a way that you can create iterators without the yield keyword. You use list comprehension syntax with (). So to carry on the rather trivial example (which is just xrange, the generator version of range):

def firstn(n):
    return (x for x in range(n)) 

Alternately, we can think of list comprehensions as generator expressions wrapped in a list constructor.

>>> list(firstn(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
icc97
  • 11,395
  • 8
  • 76
  • 90
  • 2
    This doesn't quite seem to address the question, which as I understand it is asking about `yield` as a standalone statement (as opposed to e.g. `yield num`). – David Z Mar 27 '18 at 07:11
  • 1
    @DavidZ the OP asks *"How does it work"*, then further in the comments asks [*"can I just remove it?"*](https://stackoverflow.com/questions/49506001/what-does-yield-return-if-no-argument-is-given/49506405#comment86016026_49506001). I'm explaining why you need the `yield` keyword. The answer to what is returned with no variable is already mentioned in the comments. I'll add it to remove any confusion. – icc97 Mar 27 '18 at 07:18
  • 2
    The pytest package has [examples](https://docs.pytest.org/en/latest/example/simple.html) contain: ``` outcome = yield rep = outcome.get_result() ``` I don't understand this code ...but it works and `yield` is clearly returning something other than `None`. – M Juckes Jun 25 '20 at 16:31
  • Sorry, the code should read `outcome = yield` followed by `rep = outcome.get_result()` . – M Juckes Jun 25 '20 at 16:37