0

When you create a generator object in python like this:

def gen():
    print("Hello")
    yield 1

x=gen()

print(x)

the only console output will be: < generator object gen at xxx>. Why does it not print "Hello" as well? If you change the gen function to just return a value instead of a generator (so change out "yield" with "return"), the print command is executed so that the console output is:

Hello
< generator object gen at xxx>

Why does that happen? How can I execute commands inside of generator functions?

  • 3
    try running `next(x)`. Nothing is happening because you are not iterating over the generator. – Dan Feb 26 '20 at 11:32
  • Ah, that makes sense. So the code inside of the function creating a generator is only called as soon as you iterate, not as soon as the generator itself is created. Thanks! – Poly-nom-nom-noo Feb 26 '20 at 11:38
  • Does this answer your question? [Understanding generators in Python](https://stackoverflow.com/questions/1756096/understanding-generators-in-python) – Tin Nguyen Feb 26 '20 at 11:41
  • This https://realpython.com/introduction-to-python-generators/ should help you better understand generator functions are used. – omokehinde igbekoyi Feb 26 '20 at 12:52

1 Answers1

1

There is a famous statement: everything in Python is an object. So when do this, you just assign generator to variable, that's it. You can do the similar with functions:

>>> def func():
...     pass
... 
>>> x = func
>>> x
<function func at 0x7f78f03662d0>

If you want to use the generating values, you should iterate through it, so for example:

>>> def gen():
>>>     yield 1
>>>     yield 2
>>> list(gen())
[1, 2]

In your case just use next():

>>> def gen():
>>>     print("Hello")
>>>     yield 1
>>> x=gen()
>>> print(next(x))
hello
1
ginkul
  • 1,026
  • 1
  • 5
  • 17