I wanted to write a logger-like class and wondered, "Which would be more readable, using a generator or a class?" So I wrote and compared both.
def logger(output_file): with open(output_file, 'w') as fp: while True: text = (yield None) fp.write(text + '\n') print text l = logger('test-python.log') l.next() l.send('The quick') l.send('Brown fox') l.send('Jumps over') l.send('The lazy dog.')
class Logger(object): def __init__(self, output_file): self.fp = open(output_file, 'w') def write(self, text): self.fp.write(text + '\n') print text def close(self): self.fp.close() l = Logger('test-python.log') l.write('The quick') l.write('Brown fox') l.write('Jumps over') l.write('The lazy dog.') l.close()
The quick Brown fox Jumps over The lazy dog.
Well, the class wins.
Comments