My first Python program
Jonas H.
jonas at lophus.org
Wed Oct 13 13:49:13 EDT 2010
On 10/13/2010 06:48 PM, Seebs wrote:
> Is it safe for me to assume that all my files will have been flushed and
> closed? I'd normally assume this, but I seem to recall that not every
> language makes those guarantees.
Not really. Files will be closed when the garbage collector collects the
file object, but you can't be sure the GC will run within the next N
seconds/instructions or something like that. So you should *always* make
sure to close files after using them. That's what context managers were
introduced for.
with open('foobar') as fileobject:
do_something_with(fileobject)
basically is equivalent to (simplified!)
fileobject = open('foobar')
try:
do_something_with(fileobject)
finally:
fileobject.close()
So you can sure `fileobject.close()` is called in *any* case.
>> * you might want to pre-compile regular expressions (`re.compile`)
>
> Thought about it, but decided that it was probably more complexity than I
> need -- this is not a performance-critical thing. And even if it were, well,
> I'm pretty sure it's I/O bound. (And on my netbook, the time to run this
> is under .2 seconds in Python, compared to 15 seconds in shell, so...)
Forget about my suggestion. As someone pointed out in a another post,
regular expressions are cached anyway.
> I'm a bit unsure as to how to pick the right subclass, though.
There are a few pointers in the Python documentation on exceptions.
Jonas
More information about the Python-list
mailing list