Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yield Only Once Per Iteration

I'm trying to do type conversions using a generator, but I want to move to the next element in the iterator once I successfully yield a value. My current attempt will yield multiple values in cases where the expressions are successful:

def type_convert(data):
    for item in data:
        try:
            yield int(item)
        except (ValueError, TypeError) as WrongTypeError:
            pass
        try:
            yield float(item)
        except (ValueError, TypeError) as WrongTypeError:
            pass
        yield item

How is this accomplished?

like image 938
donopj2 Avatar asked Jul 19 '12 18:07

donopj2


1 Answers

You should be able to continue this loop just like any other:

try:
    yield int(item)
    continue
except (ValueError, TypeError) as WrongTypeError:
    pass

As a side note, I've always thought continue was a strange name for this control structure...

And, here's your corrected code in action:

def type_convert(data):
    for item in data:
        try:
            yield int(item)
            continue
        except (ValueError, TypeError) as WrongTypeError:
            pass
        try:
            yield float(item)
            continue
        except (ValueError, TypeError) as WrongTypeError:
            pass
        yield item


for a in type_convert(['a','1','1.0']):
    print (a)
like image 108
mgilson Avatar answered Oct 25 '22 18:10

mgilson