---
slug: "ジェネレータとクラスでロガーっぽいのを書き比べる"
title: "Comparing Logger Implementations Using Generators and Classes"
description: "\n\nI 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."
url: "https://www.ytyng.com/en/blog/ジェネレータとクラスでロガーっぽいのを書き比べる"
publish_date: "2013-11-18T02:41:35Z"
created: "2013-11-18T02:41:35Z"
updated: "2026-02-26T22:05:03.168Z"
categories: ["Python"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/be65b26f0b594126888940ab170ab409.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

# Comparing Logger Implementations Using Generators and Classes

<div class="document">

<p>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.</p>

<div class="section" id="id1">
<h3>Generator</h3>
<pre class="literal-block">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.')
</pre>
</div>

<div class="section" id="id2">
<h3>Class</h3>
<pre class="literal-block">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()
</pre>
</div>

<div class="section" id="id3">
<h3>Output Result</h3>
<pre class="literal-block">The quick
Brown fox
Jumps over
The lazy dog.
</pre>
<p>Well, the class wins.</p>
</div>
</div>
