I've been converting Ruby code to Python code and now I'm stuck with this function that contains yield
:
def three_print():
yield
yield
yield
I would like to call the function and tell it to print "Hello" three times because of the three yield
statements. As the function does not take any arguments I get an error. Can you tell me the easiest way to get it working? Thank you.
Yield is generally used to convert a regular Python function into a generator. Return is generally used for the end of the execution and “returns” the result to the caller statement. It replace the return of a function to suspend its execution without destroying local variables.
yield in Python can be used like the return statement in a function. When done so, the function instead of returning the output, it returns a generator that can be iterated upon. You can then iterate through the generator to extract items. Iterating is done using a for loop or simply using the next() function.
Example: Yield MethodWhen the function is called, the output is printed and it gives a generator object instead of the actual value.
Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return.
yield
in Ruby and yield
in Python are two very different things.
In Ruby yield
runs a block passed as a parameter to the function.
Ruby:
def three
yield
yield
yield
end
three { puts 'hello '} # runs block (prints "hello") three times
In Python yield
throws a value from a generator (which is a function that uses yield
) and stops execution of the function. So it's something completely different, more likely you want to pass a function as a parameter to the function in Python.
Python:
def three(func):
func()
func()
func()
three(lambda: print('hello')) # runs function (prints "hello") three times
Python Generators
The code below (code you've provided) is a generator which returns None
three times:
def three():
yield
yield
yield
g = three() #=> <generator object three at 0x7fa3e31cb0a0>
next(g) #=> None
next(g) #=> None
next(g) #=> None
next(g) #=> StopIteration
The only way that I can imagine how it could be used for printing "Hello" three times -- using it as an iterator:
for _ in three():
print('Hello')
Ruby Analogy
You can do a similar thing in Ruby using Enumerator.new
:
def three
Enumerator.new do |e|
e.yield # or e << nil
e.yield # or e << nil
e.yield # or e << nil
end
end
g = three
g.next #=> nil
g.next #=> nil
g.next #=> nil
g.next #=> StopIteration
three.each do
puts 'Hello'
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With