[Python-Dev] Simplify the file-like-object interface (original) (raw)
Andrew Durdin adurdin at gmail.com
Tue Sep 13 08:50:23 CEST 2005
- Previous message: [Python-Dev] Simplify the file-like-object interface
- Next message: [Python-Dev] Simplify the file-like-object interface
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 9/6/05, Antoine Pitrou <solipsis at pitrou.net> wrote:
One could use "class decorators". For example if you want to define the method foo() in a file-like class, you could use code like:
I like the sound of this. Suppose there were a function textstream() that decorated a file-like object (supporting read() and write()), so as to add all of iter(), next(), readline(), readlines(), and writeline() that it did not already implement. Then you could wrap any file-like object easily to give it convenient text-handling:
mytextsocketstream = textstream(mysocketstream) for line in mytextsocketstream: print line
Another area where I think this approach can help is with the text/binary file distinction. file() could always open files as binary, and there could be a convenience function textfile(name, mode) which would simply return textstream(file(name, mode)). This would remove the need for "a" or "b" in the mode parameter, and make it easier to keep text- and binary-file access separate in one's mind:
tf = textfile("log.txt", "w") tf.writelines(loglist)
bf = file("img.jpg", "r") process_image_file(bf)
Finally, I think this could nicely tie into the print statement/function/method debate, as the print() method could be defined by the textstream() wrapper, allowing any text stream to support the convenient print() behaviour, but not requiring it for binary streams, for which such a function makes little sense anyway. And then textstream() could be used (in the sys module, preferably) to ensure that sys.stdout and sys.stderr both support print(). So you'd have the builtin:
Actual signature depending on which variant proposal is taken up
def print(*args, **kwargs): sys.stdout.print(*args, **kwargs)
And using print() could be a simple as:
print("Hello, World") sys.stdout.print("This is normal output") sys.stderr.print("This is an error message")
I have a vague idea that a wrapper like this (or another similar wrapper) could provide for convenient, transparent handling of Unicode text files also, but I don't know Unicode well enough to be certain.
Andrew.
- Previous message: [Python-Dev] Simplify the file-like-object interface
- Next message: [Python-Dev] Simplify the file-like-object interface
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]