Comparing Logger Implementations Using Generators and Classes

Python
2013-11-18 02:41 (12 years ago)
Comparing Logger Implementations Using Generators and Classes

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
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Categories

Archive