Buffering control in python?

Michal Wallace sabren at manifestation.com
Sat Oct 12 19:14:10 EDT 2002


On Sat, 12 Oct 2002, Fernando Pérez wrote:

> In Perl each stream can be set to unbuffered via a simple 
> 
> STDOUT->autoflush(1);


Well, I don't know if there's a built in way to do this or
not, but python is an object oriented language, so you can
either subclass the file class, or, for a more general solution,
 you can use the Proxy design pattern:



class Proxy(object):
    def __init__(self, subject):
        self.__dict__["subject"] = subject
    def __getattr__(self, attr):
        return getattr(self.__dict__["subject"], attr)
    def __setattr__(self, attr, value):
        setattr(self.__dict__["subject"], attr, value)
    def _subj(self):
        return self.__dict__["subject"]


class AutoFlush(Proxy):
    def write(self, data):
        self._subj().write(data)
        self._subj().flush()
        print "LOOK MA! I'M FLUSHING! :)"


file = AutoFlush(open("file.txt", "w"))
print >> file, "go for it!"





For some reason, this prints the "LOOK MA!" line twice when
I run it (anyone know why?), but other than that, should
work...

Proxies are so easy in python, I'm surprised we don't see
Proxy as a built-in type.

Cheers,

- Michal   http://www.sabren.net/   sabren at manifestation.com 
------------------------------------------------------------
Switch to Cornerhost!             http://www.cornerhost.com/
 Low Priced, Reliable Blog Hosting, With a Human Touch. :)
------------------------------------------------------------





More information about the Python-list mailing list