Buffering control in python?

Bengt Richter bokr at oz.net
Sat Oct 12 22:20:41 EDT 2002


On Sun, 13 Oct 2002 01:30:06 +0200, holger krekel <pyth at devel.trillke.net> wrote:

>Michal Wallace wrote:
>> On Sat, 12 Oct 2002, Fernando P=E9rez wrote:
>>=20
>> > In Perl each stream can be set to unbuffered via a simple=20
>> >=20
>> > STDOUT->autoflush(1);
>
>you can start with 'python -u ...' and get unbuffered IO.=20
>
>> 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:
>>=20
>> class Proxy(object):
>>     def __init__(self, subject):
>>         self.__dict__["subject"] =3D 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"]
>>=20
>>=20
>> class AutoFlush(Proxy):
>>     def write(self, data):
>>         self._subj().write(data)
>>         self._subj().flush()
>>         print "LOOK MA! I'M FLUSHING! :)"
>>=20
>>=20
>> file =3D AutoFlush(open("file.txt", "w"))
>> print >> file, "go for it!"
>
>the 'print "LOOK ..."' statement probably calls 'write' twice.=20
>
Yup. Checking with my little watcher makes that easy to verify:

 >>> from ut.tracewatch import TraceWatch as TW
 >>> tw = TW()
 >>> class Proxy(object):
   [... as above]

 >>> class AutoFlush(Proxy):
   [... as above]

 >>> tw.addwatch('write','#f')
 >>> tw.on()
 >>> file = AutoFlush(open("file.txt", "w"))
 >>> print >> file, "go for it!"
 --------------------------------------------------------------------
 File: "<stdin>"
 Line [scope] C:all, R:eturn eX:cept S:tack N:ew M:od E:quiv U:nbound
 ---- ------- -------------------------------------------------------
    2 [write]:           C: write(self=<__main__.AutoFlush object at 0x007D6310>, data='go for it!')
 LOOK MA! I'M FLUSHING! :)
    5 [write]:           R: write(...) => None
    2 [write]:           C: write(self=<__main__.AutoFlush object at 0x007D6310>, data='\n')
 LOOK MA! I'M FLUSHING! :)
    5 [write]:           R: write(...) => None

The '\n' goes out separately ;-)

>Yip, proxying is a nice pattern especially with python.
>
Is there a Python pattern repository somewhere?

Regards,
Bengt Richter



More information about the Python-list mailing list