Comparing Logger Implementations Using Generators and Classes

Python
2013-11-18 11:41 (11 years ago) ytyng

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.

Generator

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

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()

Output Result

The quick
Brown fox
Jumps over
The lazy dog.

Well, the class wins.

Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011