I have a piece of code (an xls parser) that does some validation on the fields and returns with yield a generator that contains every row of the xls.
Now, i have to collect validation errors in a list, and use them when the generator is exhausted.
This is a piece of code that represent the parser and a poor designed solution.
error_list = []
def gen(limit): #xls parser
for x in range(limit):
if x%2: #fake error contition
error_list.append(x)
else:
yield(x*x) #return
is there a more pythonic way to do this? i'm not a big fan of global variables.
i'd love to keep the code as it is as much as possible but if there's no other way i'll convert the function to a classic
def gen(limit): #xls parser
error_list = []
results = []
for x in range(limit):
if x%2: #fake error contition
error_list.append(x)
else:
results.append(x*x)
return results, error_list
Yes, it' still a generator.
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.
The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a 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.
A generator function cannot return out-of-band data like this.
I'd use a class instead, as an instance gives you something to stick such extra state:
class XLSParser(object):
def __init__(self, limit):
self.error_list = []
self.limit = limit
def __iter__(self):
for x in range(self.limit):
if x%2: #fake error condition
self.error_list.append(x)
else:
yield(x*x) #return
and iterate over that object:
parser = XLSParser(limit)
for result in parser:
# do something
errors = parser.error_list
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