Python 3 is killing Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jul 16 07:35:40 EDT 2014


On Wed, 16 Jul 2014 18:44:38 +1000, Chris Angelico wrote:

> On Wed, Jul 16, 2014 at 5:49 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>> ... Although I'm open to the suggestion that maybe the Pythonic way to
>> do that should be:
>>
>> print("foo bar baz", file="foo.txt")
>>
>>
> And I would argue against that suggestion, having worked with a language
> where that's the case.
[...]

> 1) Hidden global state. Somewhere there's a mapping of file names to
> open file handles, and it's not obvious. 

Absolutely not! What do you take me for, the designer of REXX???

:-P

What I had in mind was for print to open the file in append mode, write, 
then close the file. Something like this:


def print(*values, sep=' ', end='\n', file=sys.stdout, flush=False):
    def write(f):
        for value in values:
            f.write(str(value) + sep)
        f.write(end)
        if flush:
            f.flush()
    if isinstance(file, (str, bytes)):
        with open(file, 'a') as f:
            write(f)
    else:
        write(f)
        


The downside of this is that it doesn't handle encodings and error 
handlers, or any of the other, more obscure, arguments to open(). But 
since print is intended as a convenience function, I'm okay with that. If 
you need more than the default settings, you should open the file 
yourself:

f = open('something.txt', 'w', encoding='UTF=32')
print("fe fi fo fum", file=f)


> 2) Corollary: Surprising
> behaviour if you try to use a file twice in one program.

Not with my idea. The only surprises are if you try to use it with the 
filename from different threads, but that's a relatively advanced thing 
to do. If you're using print from two threads at once, don't pass a file 
name.


> 3) Closing a file is sometimes unobvious. If you terminate the program
> with open files, there's no problem, but if the program keeps running,
> its files stay open.
> 4) Very VERY occasionally, you might run into a problem with too many
> open files. (It should be noted that I learned REXX back in the 90s.
> It's entirely possible that "too many open files" would be at some
> insanely ridiculous number now.) At that point, you need to close
> something... but how can you know?

Neither of these will be a problem.

Well, technically, if you opened like a million threads, and had every 
thread try to print to a different file name at the same time, that could 
be a problem. But if you're doing that, you deserve whatever happens.

;-)



-- 
Steven



More information about the Python-list mailing list