Buffering control in python?

holger krekel pyth at devel.trillke.net
Sat Oct 12 19:30:06 EDT 2002


Michal Wallace wrote:
> On Sat, 12 Oct 2002, Fernando Pérez wrote:
> 
> > In Perl each stream can be set to unbuffered via a simple 
> > 
> > STDOUT->autoflush(1);

you can start with 'python -u ...' and get unbuffered IO. 

> 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!"

the 'print "LOOK ..."' statement probably calls 'write' twice. 

Yip, proxying is a nice pattern especially with python.

regards,

    holger




More information about the Python-list mailing list