Krasnars Krasnars - 7 months ago 13
Python Question

python generator with different different next() conditions

I nedd a python generator to get the height of the line in a pdf file.
To get this, I created a generator, which returns the height of the next line.

def height_generator(height):
while height > 0:
height -= 15
yield(height)


This works perfect so far.

But I need different heights. For example if need a new paragraph in my file, I need to reduce the height by 20 instead of 15.

to get this, I want to define, if I want a new line or a new paragrapht, when I call my generator.

I treid something like this:

def height_generator(height):
while height > 0:
def spacer(height, a):
if a == 1:
height -= 15
yield(height)
elif a ==2:
height -= 20
yield(height)


but it does not work.

Answer

You are defining a function in a while loop, which just makes your code loop infinitely.

You need to send(a) to the generator to tell it what to do. For example

def height_generator(height):
    while height > 0:
        a = yield height
        if a == 1:
            height -= 15
        else:
            height -= 20

g = height_generator(100)
g.next()
print g.send(1) # 85
print g.send(2) # 65
print g.send(1) # 50

yield is not only a way that a generator produces values to its caller, but also can be used to send values to the generator. The argument passed to send will be the value of the expression yield height. For more detail, please read PEP 255

Comments